What is the number of processes generated by forks in this code
#include <stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void) {
pid_t a,b,c;
a=fork();
b=fork();
if(a||b)
c=fork();
printf("%d %d %d\n",a,b,c);
}
So I changed this code like this, originally, it was:
#include <stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void) {
if(fork()||fork())
fork();
return 0;
}
So by that printf, I would have 5 processes, but is it correct or is it a better way to check the number of processes? Like, printing all rows and getting only the ones with 0 and some other values, after all the forks, is what I did
Solution 1:
They're not equivalent because of the short-circuiting of the ||
operator.
In the first version,
b = fork();
executes unconditionally in both the parent and the first child. So at this point there are two child processes and a grandchild process.
In the second version,
if (fork() || fork())
creates one child, and then creates a second child only in the original parent process. It doesn't create a grandchild process because the first fork()
returns 0
in the child process, so the second fork()
is skipped.
I don't think there's a way to make the two equivalent without variables.