简体   繁体   中英

Shell job control

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);  
}

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.

父进程正在调用子进程上的waitpid ,这将阻塞子进程改变状态(即终止)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM