简体   繁体   English

叉和子/父进程

[英]Fork and child/parent processes

I'm studying for a midterm for my OS class and was looking at this code example. 我正在为我的OS课程学习期中课程,并正在查看此代码示例。 On my system (OS X Yosemite) I'm getting ONE TWO FOUR TWO THREE, so it seems like the child process runs and outputs first before the parent does, despite the lack of a wait() function. 在我的系统(OS X Yosemite)上,我得到了两个,两个,三个,所以尽管缺少wait()函数,但子进程似乎先于父进程运行并输出。 Is this expected behavior on all systems, or could it also be ONE TWO THREE TWO FOUR, or even something different? 这是所有系统上的预期行为吗,或者也可能是二三四两,甚至有所不同?

#include <stdio.h>
#include <unistd.h>

int main()
{
  int rc;
  printf( "ONE\n" );
  rc = fork();
  printf( "TWO\n" );
  if ( rc == 0 ) { printf( "THREE\n" ); }
  if ( rc > 0 ) { printf( "FOUR\n" ); }
  return 0;
}

It'll print ONE , followed by: 它将显示ONE ,然后显示:

For the parent process: 对于父进程:

TWO
FOUR

For the child process: 对于子进程:

TWO
THREE

The two processes are distinct with no synchronization between them. 这两个过程是不同的,它们之间没有同步。 They run their due course, at their own timings. 他们按自己的时间安排应有的时间。

So say if the parent was faster than the child, you could get TWO FOUR followed by TWO THREE . 所以说,如果父母比孩子更快,你可以得到TWO FOUR其次是TWO THREE If the child was faster, you could get TWO THREE followed by TWO FOUR . 如果孩子是快,你可以得到TWO THREE其次是TWO FOUR If they're roughly the same, you could get a result where their outputs are intermixed, such as TWO TWO FOUR THREE , or any combination thereof. 如果他们是大致相同的,你可以得到,他们的输出混合的结果,如TWO TWO FOUR THREE ,或其任何组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM