How is it possible for fork() to return two values?

前端 未结 5 591
夕颜
夕颜 2020-12-05 15:27

Since a function in C returns only one value, all the time, how can fork(), which is also a function, return two values?

5条回答
  •  遥遥无期
    2020-12-05 15:53

    The key insight here is to think about the fact that after a fork() you have really two copies of your program. These are two processes, running the same exact copy of your code, and the execution pointer is exactly at the same line of code i.e. fork(), poised to return.

    The OS arranges for the fork() to return in the parent process with the pid of the child, and for it to return in the child process with zero (if things go well).

    That is why they say that fork() returns twice. Once in each process.

提交回复
热议问题