Home > other >  How to get into this fork() statement
How to get into this fork() statement

Time:06-17

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 */
  1. The first fork executes and if it returns a child pid_t the condition becomes true and the second condition is not evaluated because of short-circuit evaluation and the following statement is executed.
  2. if the first fork returns 0, it's the child process and the second condition is evaluated.
    • If the second fork() returns 0 (that is, it's the child process) the full expression becomes true and the following statement is executed.
  • Related