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?