What exactly does fork return?

后端 未结 8 1137
时光取名叫无心
时光取名叫无心 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
    }
    
    0 讨论(0)
  • 2020-12-02 14:27
                                 p = fork();
                            /* assume no errors */
                            /* you now have two */
                            /* programs running */
                             --------------------
          if (p > 0) {                |            if (p == 0) {
            printf("parent\n");       |              printf("child\n");
            ...                       |              ...
    
    0 讨论(0)
提交回复
热议问题