Search code examples
cforkpid

Why can "X" be the last character of output?


#include <stdio.h>
#include <sys/types.h> 
#include <sys/wait.h> 
#include <sys/types.h>
#include <unistd.h>

int main() {
    if (fork() == fork()){

        fprintf(stderr, "Z");
    }
    else {
        if (waitpid((pid_t)-1,NULL,0)!=-1) {
            fprintf(stderr, "Y");

        }
        else {
            fprintf(stderr, "X");
        }
    }
}

I was studying this program and I found out "ZYYX" can be the output. I don't quite understand why. In my understanding, there are four process in total, parent->parent, parent->child, child->parent, child->parent. And there is no doubt child->child prints Z. And child->parent prints Y after child->child prints Z. And parent->parent should wait until parent->child prints X. So why it is possible that X is printed as the last character of the output?


Solution

  • I realized that waitpid waits for any child process, so if ZY has been printed out, then Y can be printed out immediately since it has waited for "Y". Thus, X can be printed as the last character.