fork()如何知道它是否在子进程和父进程中?

执行fork()系统调用时,处理器将进入内核模式。 因此,在fork调用结束时,生成了一个新进程,其中包含堆栈,用户数据和用户程序的副本。 那么fork如何在此时决定它是否在子进程中返回0并且如果它是主父进程那么它必须返回子进程的PID。

fork()被调用两次? 请解释。 我很迷惑 !!!

调用fork() ,进程会生成具有共享或重复进程段的子进程。 这意味着在程序中,在调用fork()之前,只有一个进程或一个执行单元。 fork()返回后,有两个进程并发运行。 由于此时两个进程都具有相同的调用堆栈,因此它会将每个进程视为刚刚调用fork() 。 在父进程中, fork()的返回值是子进程的PID。 在子进程中, fork()的返回值为0。

你可以通过一个非常简单的演示来看到这个:

 #include  #include  int main(){ pid_t parent = getpid(); pid_t child = fork(); if(child != 0){ printf("I am the parent process. My PID is %d\n", parent); printf("Parent process terminating\n"); } else{ printf("I am the child process. My PID is %d\n", getpid()); printf(" My parent's PID is %d\n", parent); printf("Child process terminating\n"); } return 0; } 

这是我的笔记本电脑上运行的示例:

 $ gcc -o fork fork.c $ ./fork I am the parent process. My PID is 16048 Parent process terminating I am the child process. My PID is 16049 My parent's PID is 16048 Child process terminating $ 

请注意,运行此时,PID将不同。 此外,输出受竞争条件的影响,因此有时,父进程将在子进程完成打印之前返回到shell,因此它可能如下所示:

 $ ./fork I am the parent process. My PID is 16265 Parent process terminating $ I am the child process. My PID is 16266 My parent's PID is 16265 Child process terminating 

重要的是要理解fork()导致单个执行过程分成两个独立的单元。 由于每个进程仍然是从同一程序(或源代码)生成的,因此两个进程的行为相同。 它们的输出不同的原因仅在于fork()为父进程或子进程返回不同的值。