This is on UNIX
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc,char **argv)
{
int pid,pid1,pid2,pid3;
pid=fork();
if(pid == 0)
{
printf("C1 -- %d\n",getpid());
sleep(5);
printf("C1 -- has terminated\n");
exit(1);
}
else if(pid > 0)
{
pid1=fork();
if(pid1 == 0)
{
printf("C2 -- %d\n",getpid());
sleep(5);
printf("C2 -- has terminated\n");
exit(2);
}
else if(pid1 > 0)
{
pid2=fork();
if(pid2 == 0)
{
printf("C3 -- %d\n",getpid());
sleep(5);
printf("C3 -- has terminated\n");
exit(3);
}
else if(pid2 > 0)
{
pid3=fork();
if(pid3 == 0)
{
printf("C4 -- %d\n\n\n",getpid());
sleep(5);
printf("C4 -- has terminated\n");
exit(4);
}
else if(pid3 > 0)
{
wait(pid3);
printf("\nParent -- %d\n",getpid());
}
else
{
printf("Error on fork 4.\n");
return -4;
}
}
else
{
printf("Error on fork 3.\n");
return -3;
}
}
else
{
printf("Error on fork 2.\n");
return -2;
}
}
else
{
printf("Error on fork 1.\n");
return -1;
}
return 0;
}
I don't understand why this is not generating the following output.
Code:
C1 -- ####
C2 -- ####
C3 -- ####
C4 -- ####
C1 has terminated
C2 has terminated
C3 has terminated
C4 has terminated
Parent -- ####
I'm getting stuff like this
Code:
C1 -- ####
C3 -- ####
C2 -- ####
C4 -- ####
C1 has terminated
Parent -- ####
C2 has terminated
C3 has terminated
C4 has terminated