简体   繁体   English

fork()到底发生了什么?

[英]What exactly happens with fork()?

int main(){

    char ch;

    fork();

    cin >> c;
}

After calling fork() I should have 2 exact processes running the same code. 在调用fork()之后,我应该有2个运行相同代码的确切进程。 Why after running this simple example, I am either asked to enter a character only once, either twice? 为什么在运行这个简单的例子之后,我被要求只输入一次字符,要么两次? Shouldn't the system expect 2 inputs every single time I run this program? 我运行这个程序时,系统不应该期望每次输入2个输入吗?

>./a.out 
a
>./a.out
a
b
>

You have two processes reading from the terminal at the same time. 您有两个进程同时从终端读取。 It is anybody's guess which process gets the input. 任何人都猜测哪个进程得到了输入。

  • If the parent process gets the input first, it exits and returns control to the shell. 如果父进程首先获得输入,它将退出并将控制权返回给shell。 (Note that this actually causes a repeat of the same situation, with shell and the child process fighting for input.) (请注意,这实际上会导致重复相同的情况,shell和子进程争夺输入。)
  • If the child process gets the input first, it exits but control does not return to the shell untill the parent process exits. 如果子进程首先获得输入,它将退出但控制不会返回到shell,直到父进程退出。

You should not expect consistent behavior if you have two processes reading from the same terminal. 如果您有两个进程从同一终端读取,则不应期望一致的行为。

When fork() is called, the operating system typically copies the entire memory space of the executing program (sort of). 当调用fork()时,操作系统通常会复制正在执行的程序的整个内存空间(排序)。 Both programs then run. 两个程序然后运行。 The only differences is that in the "new" process, fork() returns 0, and in the "old" process it returns the process ID of the new process. 唯一的区别是在“new”进程中,fork()返回0,而在“old”进程中,它返回新进程的进程ID。

The reason that you're only asked for one input is that one of the programs is running in the background. 您只需要一个输入的原因是其中一个程序在后台运行。 The command-line shell only does I/O for one process at a time. 命令行shell一次只对一个进程执行I / O操作。

fork() creates a child process. fork()创建一个子进程。

But which process (among the parent and the newly born child) gets the CPU slice is undetermined. 但是哪个进程(在父级和新生的子级中)得到CPU切片是不确定的。 When both the processes are blocked for keyboard input, either the child or the parent can get the input. 当两个进程都被阻止进行键盘输入时,子进程或父进程都可以获得输入。 If the parent gets the token, it reads the input into its variable defined in its address space and exits. 如果父获取令牌,它将输入读入其地址空间中定义的变量并退出。 And the child never gets a chance to read from the input. 孩子从来没有机会从输入中读取。 And this orphaned child process will then be adopted by the 'root' process (pid=1). 然后,这个孤立的子进程将被'root'进程采用(pid = 1)。 See ps output. 请参阅ps输出。

And in the other case, where the child gets the token and reads the data and exits, the parent is still alive and hence blocks for input again. 而在另一种情况下,当孩子获得令牌并读取数据并退出时,父母仍然活着,因此再次阻止输入。

在fork()之后包含wait()并尝试。

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

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