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