What exactly does fork return?

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

    This is the cool part. It's equal to BOTH.

    Well, not really. But once fork returns, you now have two copies of your program running! Two processes. You can sort of think of them as alternate universes. In one, the return value is 0. In the other, it's the ID of the new process!

    Usually you will have something like this:

    p = fork();
    if (p == 0){
        printf("I am a child process!\n");
        //Do child things
    }
    else {
        printf("I am the parent process! Child is number %d\n", p);
        //Do parenty things
    }
    

    In this case, both strings will get printed, but by different processes!

提交回复
热议问题