Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell job control

Tags:

c

shell

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);  
}
like image 815
user1535672 Avatar asked Oct 22 '25 15:10

user1535672


2 Answers

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.

like image 161
BenTrofatter Avatar answered Oct 24 '25 06:10

BenTrofatter


The parent process is calling waitpid on the child, which will block until the child process changes state (i.e. terminates).

like image 23
gcbenison Avatar answered Oct 24 '25 06:10

gcbenison