Reputation: 4284
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;
}
Upvotes: 2
Views: 863
Reputation: 30803
pid2
is not initialized in the parent process case. How much B
will be printed is undefined behavior.
pid=fork()
doesn't execute main()
again, hopefully ...
Upvotes: 1
Reputation: 2206
he return value of the Fork call returns a different value depending in which proccess you currently are.
Let's say you want some code to be executed in the parent process you would pu that part of the code in this condition block :
p = fork();
if (p > 0)
{
// We're the parent process
}
And if you want to execute some code in the child process the same would apply :
p = fork();
if (0 == p)
{
// We're the child process
}
And the rest (executed by both parents process and child) in a else block.
Upvotes: 0
Reputation: 662
Fork return 2 values:
In your example, you create 3 processes and will output 2A, 1B and 3C
Upvotes: 2
Reputation: 182609
The fork
system 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".
Upvotes: 6
Reputation: 61427
fork
returns 0
to the child process and the pid of the child to the parent process. The man pages should clear everything else up.
Upvotes: 3