How does fork() work?

前端 未结 4 1498
有刺的猬
有刺的猬 2020-11-28 08:03

Im really new to forking, what is the pid doing in this code? Can someone please explain what comes out at line X and line Y ?

#include 
#         


        
4条回答
  •  悲哀的现实
    2020-11-28 08:13

    fork() duplicates the process, so after calling fork there are actually 2 instances of your program running.

    How do you know which process is the original (parent) one, and which is the new (child) one?

    In the parent process, the PID of the child process (which will be a positive integer) is returned from fork(). That's why the if (pid > 0) { /* PARENT */ } code works. In the child process, fork() just returns 0.

    Thus, because of the if (pid > 0) check, the parent process and the child process will produce different output, which you can see here (as provided by @jxh in the comments).

提交回复
热议问题