Can the order of execution of fork() be determined?

前端 未结 5 1719
温柔的废话
温柔的废话 2020-11-28 13:33

I\'m working on an exercise on the textbook \"Operating System Concepts 7th Edition\", and I\'m a bit confused about how does fork() work. From my understanding

5条回答
  •  生来不讨喜
    2020-11-28 13:59

    While you cannot control which process (parent or child) gets scheduled first after the fork (in fact on SMP/multicore it might be both!) there are many ways to synchronize the two processes, having one wait until the other reaches a certain point before it performs any nontrivial operations. One classic, extremely portable method is the following:

    1. Prior to fork, call pipe to create a pipe.
    2. Immediately after fork, the process that wants to wait should close the writing end of the pipe and call read on the reading end of the pipe.
    3. The other process should immediately close the reading end of the pipe, and wait to close the writing end of the pipe until it's ready to let the other process run. (read will then return 0 in the other process)

提交回复
热议问题