简体   繁体   English

了解UNIX中的fork系统调用

[英]Understanding the fork system call in UNIX

I'm trying to understand both the execution order of a line of code given to me earlier and process creation using the fork() system call. 我试图同时了解之前给我的代码行的执行顺序和使用fork()系统调用进行的流程创建。 It's in C language for running on UNIX. 它使用C语言在UNIX上运行。

I understand the main concept behind fork() , nevertheless, I want to understand the process tree creation derived from the following line of code: 我了解了fork()背后的主要概念,但是我想了解从以下代码行派生的流程树的创建:

x = fork() || !fork();

Any help will be greatly appreciated! 任何帮助将不胜感激!

The initial parent-process who runs the code (let's say its is PID = 1000 ), executes the x = fork() part, and spawns a new child-process (let's say PID = 1001 ). 运行代码的初始父进程(假设它是PID = 1000 ),执行x = fork()部分,并产生一个新的子进程(假设PID = 1001 )。

For process PID = 1000 , the value of the logical expression so far is non-zero, because fork(2) returns its child's pid . 对于进程PID = 1000 ,到目前为止,逻辑表达式的值非零,因为fork(2)返回其子项的pid Thus, due to short circuit evaluation , the rest part of the logical expression isn't evaluated as it's not needed. 因此,由于短路评估 ,逻辑表达式的其余部分由于不需要而未评估。

For process PID = 1001 , the value of the logical expression so far is 0 , because in the case of the new process created, fork(2) returns 0 ; 对于流程PID = 1001 ,到目前为止,逻辑表达式的值为0 ,因为在创建新流程的情况下, fork(2)返回0 so it has to evaluate the rest part of the logical expression too. 因此它也必须评估逻辑表达式的其余部分。 It executes the !fork() part, spawning a new process (let's say PID = 1002 ). 它执行!fork()部分,产生一个新进程(假设PID = 1002 )。

The process tree derived is the following: 派生的过程树如下:

       1000
        |
        |
       1001
        |
        |
       1002

chrk's answer is great, in addition, fork() return 2 times, one is pid of child process in parent process, the other is 0 returned from child process. chrk的答案很好,此外, fork()返回2次,一个是父进程中子进程的pid,另一个是子进程中返回的0。 Both processes continue to process after fork() returns. fork()返回之后,两个过程都继续处理。

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

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