3

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?

  • Actually, That what I was wondering about. Are parent and child process deterministic or non-deterministic? And after fork() will the processor finish parent process first or its child process first? I had the assumption that parent process start -> fork -> exit, then its child process would start running from fork(). – SopanhavuthSom Oct 5 '15 at 20:01
  • Nondeterministic. The child may get ahead of the parent, the parent may get ahead of the child, or they might run simultaneously on two cores. You're at the mercy of your system's scheduler. If you need synchronization, you need to synchronize the two processes explicitly via some form of IPC. – PSkocik Oct 5 '15 at 22:13
2

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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.