4

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;
}
Mr. Kevin
  • 41
  • 1
  • 1
  • 2
  • 1
    The first child will become a zombie until the father exits, then it will become an orphan. – Barmar Oct 13 '16 at 07:48
  • @Barmar But how is it possible? The first child (that becomes a zombie) also exits. – Mr. Kevin Oct 13 '16 at 07:53
  • 1
    A process becomes an orphan if its parent exits without waiting for it. That's true even if the child has already exited. When it becomes an orphan, `init` adopts it, waits for it, and the process goes away. – Barmar Oct 13 '16 at 07:55
  • @Barmar So, both child processes become orphan? – Mr. Kevin Oct 13 '16 at 08:00
  • 1
    No. The process that you wait for with `waitpid()` doesn't become an orphan, because you wait for it. – Barmar Oct 13 '16 at 08:02

1 Answers1

4

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.

Ayak973
  • 468
  • 1
  • 6
  • 23