I am studying about system programming system calls. I have a code block in my assignment (given below). The question asks me to how many A,B or C will be printed. My question is what is the meaning of if(pid == 0)? I guess if(pid == 0) means false, so I analyse that 2 x A and 2 x B will be printed. Am I write or? Second question is does pid2 = fork() executes main again?
int main()
{
int pid,pid2;
int i;
pid = fork();
printf("A\n");
if (pid == 0)
pid2=fork();
if (pid2)
printf("B\n");
printf("C\n");
return 0;
}
The
forksystem call is special. You call it once and it returns twice. Once in the child and once in the parent.In the parent it returns the pid of the child and in the child it returns 0. Thus,
if (pid == 0)means “if this is the child“.