I am making a shell and I am confused as to what to do if a command is to be put in the background. I have parsed my commands, and fork works for commands that are in the foreground. I have it so it can be determined if a command is to be put in the background. I'm not really sure what to do in the first else if of my code. Any pointers on how to approach background commands would be appreciated.
pid_t childpid;
int status;
childpid = fork();
if (childpid >= 0) // fork succeeded
{
if (childpid == 0 && background == 0) // fork() returns 0 to the child
{
if (execv(path, strs) < 0)
{
perror("Error on execv.");
}
exit(0); // child exits
}
else if (childpid == 0 && background ==1)
{
// What goes here?
}
else // fork() returns new pid to the parent
{
wait(&status);
}
}
else // fork returns -1 on failure
{
perror("fork"); // display error message
exit(0);
}
The child doesn't care if it's run in the background or not, so just call exec as usual. It's in the parent process you have to behave differently.
First of all you can no longer use wait as that will block the parent process. Instead you can use waitpid with a negative pid and the WNOHANG flag to check for terminated child processes without blocking.
Another common solution that doesn't involve calling waitpid at regular intervals is to use the SIGCHLD signal, which will be raised when a child process is stopped or terminated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With