Number of possible combinations of fork

怎甘沉沦 提交于 2019-12-08 08:08:05

问题


int main(void) { 
  int id = 0;
  for(int i = 1; i < 4; i++) {
    if(fork() == 0) {
      id = i;
    } else {
      printf("Process %d created child %d\n", id, i);
    }
  }
  return 0;
}

In the code above, multiple ordering of the output (printf statements) can be generated based on how the operating system schedules processes for execution. How many different orderings are possible? You may assume that all fork and printf calls succeed.

I'm trying to help my students understand how to approach this problem, however I got a nice 0 on this question when I wrote the exam. I was hoping someone could explain how to go about it?


回答1:


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


来源:https://stackoverflow.com/questions/55622057/number-of-possible-combinations-of-fork

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