Reputation: 193
For my school project I am implementing a shell and I need help with job control.
If we type a command, say cat &
, then because of the &
it should run in background, but it's not working. I have this code:
{
int pid;
int status;
pid = fork();
if (pid == 0) {
fprintf(stderr, "Child Job pid = %d\n", getpid());
execvp(arg1, arg2);
}
pid=getpid();
fprintf(stderr, "Child Job pid is = %d\n", getpid());
waitpid(pid, &status, 0);
}
Upvotes: 4
Views: 1610
Reputation: 2158
Rather than just going straight to waiting, you should set up a signal handler for the SIGCHLD signal. SIGCHLD is sent whenever a child process stops or is terminated. Check out the GNU description of process completion.
The end of this article has a sample handler (which I've more or less copied and pasted below). Try modeling your code off of it.
void sigchld_handler (int signum) {
int pid, status, serrno;
serrno = errno;
while (1) {
pid = waitpid(WAIT_ANY, &status, WNOHANG);
if (pid < 0) {
perror("waitpid");
break;
}
if (pid == 0)
break;
/* customize here.
notice_termination is in this case some function you would provide
that would report back to your shell.
*/
notice_termination (pid, status);
}
errno = serrno;
}
Another good source of information on this subject is Advanced Programming in the UNIX Environment, chapters 8 and 10.
Upvotes: 3
Reputation: 11963
The parent process is calling waitpid
on the child, which will block until the child process changes state (i.e. terminates).
Upvotes: 1