I am having such trouble figuring out how this piece of code works -
if(fork()||!fork())
I know the first fork creates a child for the initial process, and !fork() creates a child for the previous child. But for which process do we enter the if condition? If I was wrong earlier, please correct me!
CodePudding user response:
The easiest way to understand this is to convert the || expression to separate if statements that implement the short-circuiting.
if (fork()) {
// This is the parent process
/* body */
} else {
// This is the child process
if (!fork()) {
// This is the grandchild process
/* body */
}
}
Where /* body * is whatever was in the body of the original if statement.
Since fork() returns non-zero in the parent process, the body is executed in the parent after creating the first child, and in the grandchild.
CodePudding user response:
if(fork()||!fork()) /* statement */
- The first
forkexecutes and if it returns a childpid_tthe condition becomestrueand the second condition is not evaluated because of short-circuit evaluation and the following statement is executed. - if the first
forkreturns0, it's the child process and the second condition is evaluated.- If the second
fork()returns0(that is, it's the child process) the full expression becomestrueand the following statement is executed.
- If the second
