So I wrote this code on C. I created a father, that has two child processes, and one becomes zombie. After one second it exits, and the father, that was waiting for him, finishes. The other child process remains orphan, and then finishes. My question is, what happens if I change the wait
for waitpid
.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid;
int status, value;
pid = fork();
if (pid > 0) { // Father
pid = fork();
if (pid > 0) { // Father
wait(&status);
value = WEXITSTATUS(status);
if (value == 2)
printf("Child 2");
else if (value == 3)
printf("Child 1");
} else if (pid == 0) { //Child 2 - Orphan
sleep(4);
exit(2);
} else {
exit(1);
}
} else if (pid == 0) { // Child 1 - Zombie
sleep(1);
exit(3);
} else {
printf("Error al ejecutar el fork");
exit(1);
}
return 0;
}
Quoting wait/waitpid,
The waitpid() function is provided for three reasons:
To support job control
To permit a non-blocking version of the wait() function
To permit a library routine, such as system() or pclose(), to wait for its children without interfering with other terminated children for which the process has not waited
and
The waitpid() function shall be equivalent to wait() if the pid argument is (pid_t)-1 and the options argument is 0. Otherwise, its behavior shall be modified by the values of the pid and options arguments.
So the behavior of waitpid() depends on its arguments.