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

时间:2014-01-27 17:19:16

标签: c linux operating-system

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

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

1 个答案:

答案 0 :(得分:5)

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

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

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

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()为父或子进程返回不同的值。

相关问题