Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code execute printf 8 times from forking?

Tags:

c

fork

printf

Studying for finals, I got stuck on this problem. They ask how many times the following code executes printf:

#include    "csapp.h"
void    doit()  {   
Fork();
Fork();
printf("hello\n");
return; 
}
int main()
{
doit();
printf("hello\n");
exit(0);
}

The solutions say that it printf executes 8 times, but I cannot figure out why. I've been trying to draw the picture of what's going on in the code, but my pictures make it seem like it only execute 4 times.

like image 888
Ryan Fasching Avatar asked Apr 09 '26 23:04

Ryan Fasching


1 Answers

2 forks - Four processes. Each process has two printfs with hello (one in main and one in doit - hence 8.

like image 98
Ed Heal Avatar answered Apr 12 '26 14:04

Ed Heal