What exactly does fork return?

后端 未结 8 1162
时光取名叫无心
时光取名叫无心 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:02

    Processes are structured in a directed tree where you only know your single-parent (getppid()). In short, fork() returns -1 on error like many other system functions, non-zero value is useful for initiator of the fork call (the parent) to know its new-child pid.

    Nothing is as good as example:

    /* fork/getpid test */
    #include 
    #include      /* fork(), getpid() */
    #include 
    
    int main(int argc, char* argv[])
    {
        int pid;
    
        printf("Entry point: my pid is %d, parent pid is %d\n",
               getpid(), getppid());
    
        pid = fork();
        if (pid == 0) {
            printf("Child: my pid is %d, parent pid is %d\n",
                   getpid(), getppid());
        }
        else if (pid > 0) {
            printf("Parent: my pid is %d, parent pid is %d, my child pid is %d\n",
                   getpid(), getppid(), pid);
        }
        else {
            printf("Parent: oops! can not create a child (my pid is %d)\n",
                   getpid());
        }
    
        return 0;
    }
    

    And the result (bash is pid 2249, in this case):

    Entry point: my pid is 16051, parent pid is 2249
    Parent: my pid is 16051, parent pid is 2249, my child pid is 16052
    Child: my pid is 16052, parent pid is 16051
    

    If you need to share some resources (files, parent pid, etc.) between parent and child, look at clone() (for GNU C library, and maybe others)

提交回复
热议问题