Brian Bowen Brian Bowen - 7 months ago 39
Bash Question

C- Reaping Child Process and Background

pid_t pid;

if ((pid == fork()) == 0){
if (execvp(arg[0], arg) < 0) {
printf("%s: Command not found.\n", arg[0]);
exit(0);
}

}

if (background == 0 )
{
int status;
if (waitpid(pid, &status, 0) < 0)
printf("waitfg: waitpid error");
while(waitpid(-1, 0, WNOHANG) >= 0){}


}
else
{
printf("%d %s", pid, cmdline);
}


I have this code for my program and I am trying to have the parent reap all child processes and the problem is that it is still not reaping. I am trying to use the code:

while(waitpid(-1, 0, WNOHANG) >= 0){}


in order to reap but it seems to not get rid of the zombie process. What am I supposed to do to reap instead then

Also I am not sure if I am doing background right here.

Answer

Your code is wrong:

pid_t pid;

if ((pid == fork()) == 0){  // PROBLEM HERE
        if (execvp(arg[0], arg) < 0) {
            printf("%s: Command not found.\n", arg[0]);
            exit(0);
        }

}

you compare pid which isn't initialized with result of fork() => Undefined behavior (and after, you compare the result of this comparison with 0)

You should replace if ((pid == fork()) == 0){ by if ((pid = fork()) == 0){

Comments