Question about behavior of fork()
within a loop. When fork()
is called, assuming wait()
isn't called, the parent process should continue through the code and loop back to the top where it prompts you to enter q
to quit. The forked child should print its ID and the break immediately since pid
should be equal to the child's ID and not 0. Instead, it goes into infinite loop.
Can anybody tell me what I'm misunderstanding?
int main (int argc, char *argv[])
{
char run[2];
int pid=0;
while (run[0]!= 'q')
{
printf("Type q to quit \n");
fgets (run, 2, stdin);
pid=fork();
//wait();
printf("child ID: %i\n", pid);
if(pid!=0) { break;}
}
}
You have the return values of fork()
mixed up. The child gets 0
and the parent gets the child's PID.
Editorial note: Your program causes undefined behaviour on the first iteration of the loop, since you didn't initialize run
. You should probably check the return value of fgets
, too.