What exactly does fork return?

后端 未结 8 1126
时光取名叫无心
时光取名叫无心 2020-12-02 13:51

On success, the PID of the child process is returned in the parent’s thread of execution, and a 0 is returned in the child’s thread of e

8条回答
  •  时光取名叫无心
    2020-12-02 14:25

    I'm not sure how the manual can be any clearer! fork() creates a new process, so you now have two identical processes. To distinguish between them, the return value of fork() differs. In the original process, you get the PID of the child process. In the child process, you get 0.

    So a canonical use is as follows:

    p = fork();
    if (0 == p)
    {
        // We're the child process
    }
    else if (p > 0)
    {
        // We're the parent process
    }
    else
    {
        // We're the parent process, but child couldn't be created
    }
    

提交回复
热议问题