父流程与主流程之间的区别以及如何检测主流程?

Eas*_*mer 0 c fork

在下面的示例中,我创建了3个其他过程,并且我还有1个主要过程。因此,总共有四个正在执行的过程。我的问题是,可以通过控制fork系统调用函数的返回值来检查哪个进程是父进程,哪个进程是子进程。但是,如何检测主流程执行情况?主流程和父流程之间有什么区别?

#include <stdio.h> 
#include <unistd.h>
#include <sys/types.h> 
int main() 
{ 
    int a =fork(); 
    int b =fork(); 


    if (a == 0) 
        printf("Hello from Child(A)!\n"); 

    // parent process because return value non-zero. 
    else
        printf("Hello from Parent(A)!\n"); 

    if (b == 0) 
        printf("Hello from Child(B)!\n"); 

    // parent process because return value non-zero. 
    else
        printf("Hello from Parent(B)!\n"); 


    return 0; 
} 
Run Code Online (Sandbox Code Playgroud)

San*_*ker 5

您的代码创建4个过程:

  • (a > 0) && (b > 0) :原始过程
  • (a == 0) && (b > 0) :原始流程的第一个子流程(子流程A)
  • (a > 0) && (b == 0) :原始流程的第二个子流程(子流程B)
  • (a == 0) && (b == 0) :子项A(子项AA)的第一个子进程

请记住,这将fork创建一个子进程,并在父进程中返回此子进程的pid,并在子进程中返回0。