Number of possible combinations of fork

别来无恙 提交于 2019-12-08 16:45:37

I haven't worked out all the combinations at the end, but this should get you going.

You start with a parent process. It will call fork() 3 times, and print

Process 0 created child 1
Process 0 created child 2
Process 0 created child 3

After its first fork there's one child process with id = 1. This process will continue the loop, so it will print

Process 1 created child 2
Process 1 created child 3

The parent process will then fork a child with id = 2. This process will also continue its loop, so it will print

Process 2 created child 3

That's all the first generation children. But child 1 also forks its own child 2, which will print

Process 2 created child 3

All the processes that are forked when i = 3 exit the loop immediately. They don't fork any more children, or print anything, so they can be ignored.

Each process prints its own messages in order, but they can be interspersed in any order between the processes. The one constraint is that a a child can't print anything before its parent prints the message saying that it created an earlier child, because the message is printed before the iteration that creates the child (I'm assuming output is line buffered). But it can print its own messages before the message that says it was created!

So the first two messages can be either:

Process 0 created child 1
Process 1 created child 2

or

Process 1 created child 2
Process 0 created child 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!