子进程的进程父 ID 与父进程的 PID 不同
Process parent ID of child process is different from PID of parent
我正在尝试使用 C 中的 fork()
函数在 Linux 中处理多个进程,这是我的代码:
p1 = fork();
if(p1 != 0){
p2 = fork();
}
printf("My PID is %d\n",getpid());
printf("My parent PID is %d\n",getppid());
现在假设父进程 ID 为 100,两个子进程(p1、p2)ID 为 101 和 102,init 进程 PID 为 0 我的预期输出为:
My PID is 100
My parent PID is 0
My PID is 101
My parent PID is 100
My PID is 102
My parent PID is 100
相反,我看到了不同的东西,两个子进程具有相同的 PPID,但第一个进程具有不同的 PID。这是我得到的示例输出:
My PID is 3383
My parent PID is 3381
My PID is 3387
My parent PID is 1508
My PID is 3386
My parent PID is 1508
我的问题是,两个子进程的父PID不应该是3383吗?
希望有人能解释一下这一切是如何运作的,以及我在做什么(或想)错了什么。
[从评论中确认]
您的输出取决于时间。如果父进程在子进程之后完成,您的输出将符合预期。
如果父进程在子进程之前结束,输出可能会出乎意料(在父进程不存在之前,父进程id会不同)。一旦父进程死亡(结束),init 或其他一些 实现定义的 进程(在您的情况下为 1508),将成为子进程(ren)的新父进程。这样的子进程称为孤儿进程。
根据单一 UNIX 规范第 2 版的 exit 手册页:
The parent process ID of all of the existing child processes and zombie processes of the calling process shall be set to the process ID of an implementation-defined system process. That is, these processes shall be inherited by a special system process.
为避免这种情况,请确保在获取父 pid 时父进程处于活动状态。一种方法是在退出之前在父(或所有)进程中添加一个等待。
您的代码没有任何问题
只是你的父进程在子进程完成之前退出
因此它们成为孤儿并被 init 或任何实现定义的进程(在您的情况下为 1508)采用。
试试puttin wait();让父进程完成所有子进程的执行。
我正在尝试使用 C 中的 fork()
函数在 Linux 中处理多个进程,这是我的代码:
p1 = fork();
if(p1 != 0){
p2 = fork();
}
printf("My PID is %d\n",getpid());
printf("My parent PID is %d\n",getppid());
现在假设父进程 ID 为 100,两个子进程(p1、p2)ID 为 101 和 102,init 进程 PID 为 0 我的预期输出为:
My PID is 100
My parent PID is 0
My PID is 101
My parent PID is 100
My PID is 102
My parent PID is 100
相反,我看到了不同的东西,两个子进程具有相同的 PPID,但第一个进程具有不同的 PID。这是我得到的示例输出:
My PID is 3383
My parent PID is 3381
My PID is 3387
My parent PID is 1508
My PID is 3386
My parent PID is 1508
我的问题是,两个子进程的父PID不应该是3383吗? 希望有人能解释一下这一切是如何运作的,以及我在做什么(或想)错了什么。
[从评论中确认]
您的输出取决于时间。如果父进程在子进程之后完成,您的输出将符合预期。
如果父进程在子进程之前结束,输出可能会出乎意料(在父进程不存在之前,父进程id会不同)。一旦父进程死亡(结束),init 或其他一些 实现定义的 进程(在您的情况下为 1508),将成为子进程(ren)的新父进程。这样的子进程称为孤儿进程。
根据单一 UNIX 规范第 2 版的 exit 手册页:
The parent process ID of all of the existing child processes and zombie processes of the calling process shall be set to the process ID of an implementation-defined system process. That is, these processes shall be inherited by a special system process.
为避免这种情况,请确保在获取父 pid 时父进程处于活动状态。一种方法是在退出之前在父(或所有)进程中添加一个等待。
您的代码没有任何问题
只是你的父进程在子进程完成之前退出 因此它们成为孤儿并被 init 或任何实现定义的进程(在您的情况下为 1508)采用。
试试puttin wait();让父进程完成所有子进程的执行。