1

I'm trying to write basic shell program that will manage job control with background processes. I understand to send a process to the background you call fork(), but don't wait for it in the parent. However, I also know you need to call waitpid() with the WNOHANG option to get the status of a process that has finished executing. My question is when and how to call the waitpid() in my code in order to know when a child finishes. Here's what I have so far for just executing a process in the background:

for (;;) {
    char buff[PATH_MAX + 1];                    
    char *cwd = getcwd(buff, PATH_MAX + 1);
    printf("%s/", cwd); 
    char *cmd = readline("shell>");  //This code just sets up a cmd prompt 
    if (strcmp(tokList[0], bgCmd) == 0) {
        //If the user inputs 'bg' then run the command in the background parent
        pid_t child_pid = fork();
        if (child_pid == 0) {
            execvp(bgTokList[0], bgTokList);  // This array contains just the arguments to be executed
            perror("execvp");
            return -1;
        } else {
            //parent
        }
    }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
purelyp93
  • 65
  • 1
  • 9

1 Answers1

2

When a child process has completed, the parent will receive the signal SIGCHLD. Your signal handler can then reap the status.

Using an existing example, you can modify it for your own needs.

Community
  • 1
  • 1
jxh
  • 69,070
  • 8
  • 110
  • 193