How would I calculate how many "hello world" are printed after the execution of this program. Based on how fork works, we know that fork returns non-zero value as a parent process, and a child process returns 0.
I have worked with fork() before, and calculating fork count when in loops, but have not done anything with conditional statements, how would I begin to break this problem down?
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
(fork() && fork() || fork() && fork() || fork() && fork() && fork());
printf("hello world");
return 0;
}
To better understand what's going on you should try to draw a tree with parent and children processes.
Consider that after a fork():
that means:
Visualizing the trees related with much simpler cases than yours:
fork() && fork() && fork()
P
/ | \
C1 C2 C3
fork() || fork() || fork()
P
/
C1
/
C2
/
C3
As a suggestion, if you want to understand more about what's going on and be able to build the tree, replace your printf() with:
printf("hello world - pid %d, ppid %d\n", getpid(), getppid());
so you can understand more easily how the process tree has been created.