Unix & Linux
linux process c fork
Updated Sun, 24 Jul 2022 18:37:54 GMT

Why does a "child" process finish before its parent?


This is the code example given:

# include <stdio.h>
# include <unistd.h>
void main() {
    static char *mesg[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
    int display(char *), i;
for (i=0; i<10; ++i)
    display(mesg[i]);
sleep(2);
}
int display(char *m) {
char err_msg[25];
switch (fork()) {
    case 0:
        execlp("/bin/echo", "echo", m, (char *) NULL);
        sprintf (err_msg, "%s Exec failure", m);
        perror(err_msg); return(1);
    case -1:
        perror ("Fork failure"); return(2);
    default:
        return(0);
}
}

Now, my assumption before running this program is that the parent would finish before their child. So my expected-output is

0
1
2
3
4
5
6
7
8
9

However, each time i run the program i would get a random order of process. My question is "why?". Is it because of "context switching" where the processor would jump between processes? Is it "resource allocation" where some processes get more than other? Is the order of parent and child process not set in stone and that is why we have zombie and orphan process?




Solution

The child processes start running as soon as you fork(), in fact they do not even "start", they just continue in the code after the fork() invocation, just like the parent does. Only the return value of fork() is different. Parent and child can exit in either order. So yes, context switching will make all the processes executed in random.

You'll get zombie processes when a child process exits and the parent doesn't properly "reap" the child exit code. Zombie processes basically only consist of yet-to-be-retrieved exit codes, and every time you see one, blame the parent process for not taking care. (Zombies are a bug in the parent, except if the parent is short-lived and doesn't need to take care.) If the parent exits before the child, the child process will be reparented to PID 1 which will do the exit code reaping. (It will also clean up any zombies the process had.)