blob84
1
i'm experimenting fork function and i found this code
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <wait.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fd[2];
pid_t p;
p = fork();
fork();
if (p>0) { fork();}
fork();
fork();
sleep(30);
exit(0);
}
I thought that there were 2^5 processes after running this code , but there were less processes.
Why?
NH2
2
Because when fork() returns, 2 processes exist: one parent, and one child.
- So after the first fork(), you have 2 processes.
- This 2 processes calls fork() again; you have now 4 processes.
- The third fork() is only performed by the children, resulting 4 more processes (now 6=4+2 in total).
- These 6 processes calls fork() twice, resulting 2*2*6 = 24 processes in total.
From this, it should be clear that several fork() one after the other causes an exponential growth of the number of processes.
Cheers,
/Lew
The relationship between fork and the number of processes created isnt 2^n but 2n...and in this program it will be 2n-2 due to...if (p>0) { fork();}
1 Like
NH2
4
May I suggest to check this assumption against reality by writing a small program?
Thanks,
/Lew
1 Like
Non zero return value goes to parent not child...and after double cheking my calculations yes it will be 24 procs.
NH2
7
Thanks shamrock for double checking.
Cheers,
/Lew
blob84
8
thanks NH2 for explanation!