I have read online that in the code below a child process will create another child process and Hello will be printed once.
if (fork()==fork()) printf("Hello\n"); So the father (0) will create 2 child processes (1),(2) and child (1) will create another child process (3). So only child 1 has a child and in the output Hello will indeed be printed once although there will be 4 processes in total.
But what about the next code:
int i; for (i=0; i<2; i++) if (fork()==fork()) printf("Hello\n"); I know there are 16 running processes in total. If i count using the same method as before then there are 7 child processes that each have a child process, but the output will be only 5 times "Hello". can anyone please explain this?
fork() == fork(), so it isn't meaningful to ponder about what it will do. It's the same category of questions as "what happens if I toss a handful of nails into the microwave oven" or "what happens if I put my cat in the washing machine"... please just never do that. Just pondering about it is disturbing in itself.if(fork()==fork())splits into 4 and one of the prints "Hello". The secondif(fork()==fork())splits into 4 and one of them prints "Hello". If you are just looking at the number splits, you might think that the second and third calls to fork() have some relation to each other, and therefore end up with the number 7. They do not.