Explanation of a output of a C program involving fork()

前端 未结 2 1299
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 19:07

Running this program is printing \"forked!\" 7 times. Can someone explain how \"forked!\" is being printed 7 times?

#include
#include

        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 20:02

    There're several concepts being used here, first one is knowing what fork does and what it returns in certain circumstances. Shortly, when it gets called, it creates a duplicate process of the caller and returns 0 (false for logical expressions) in child process and non-zero (true for logical expressions) for parent process. Actually, it could return a negative (non-zero) value in case of an error, but here we assume that it always succeeds.

    The second concept is short-circuit computation of logical expressions, such as && and ||, specifically, 0 && fork() will not call fork(), because if the first operand is false (zero), then there's no need to compute the second one. Similarly, 1 || fork() will not call fork() neither.

    Also note that in child processes the computation of the expression continues at the same point as in the parent process.

    Also, note that the expression is computed in the following order due to precedence:

    (fork() && fork()) || (fork() && fork())
    

    These observations should lead you to the correct answer.

    Consider the simplified example of fork() && fork()

       fork()        
      /     \
    false   true && fork()
                    /   \
                 false  true
    

    So here we have three processes created, two of which return false as the result and one returning true. Then for || we have all the processes returning false trying to run the same statement again, so we have 2 * 3 + 1 = 7 as the answer.

提交回复
热议问题