~/ learn/ comp-325/ cards/ A call that returns twice, and a corpse that needs collecting
1 of 12

The three-way branch on one return value

The three-way branch on one return value

Answer

pid_t pid = fork(); if (pid == -1) perror("fork"); else if (pid == 0) printf("child pid=%d ppid=%d\n", getpid(), getppid()); else printf("parent pid=%d child=%d\n", getpid(), pid);

Both processes run this whole block; they take different branches only because fork() handed them different values. 0 is the child, a positive number is the parent, -1 means no child was created.

S&K 3e ch19 §19.3.2–19.3.6 and Figure 19.7; fork/wait/waitpid and the <sys/wait.h> macros per POSIX.1-2024

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/1ee8de8c-7f41-458e-99cf-d212069aa140/flashcard utf-8 LF