1

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;} } } 

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've run into that undefined behavior bug several times, in commercial and in open source code bases. It is evil because it almost always works correctly until that one time the stack does contain a 'q' or a -1, or whatever it is.
It can also be useful to print the value of run after the fgets() because you'll be getting one character at a time, first the character you type, then the newline, etc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.