提问人:Rama Zain 提问时间:11/11/2023 最后编辑:Jonathan LefflerRama Zain 更新时间:11/12/2023 访问量:35
子程序打印了错误的父 ID(C 程序) 程序应该打印与第一个 print 语句相同的进程 ID?
the child is printing a wrong parent id (c program) the program is supposed to print the same process id as the first print statement?
问:
它总是给我 707 的父进程! 它应该提供 pid1 id 吗?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1 = getpid();
printf("the parent id is %d \n", pid1);
if (pid1 % 2 != 0) {
printf("the parent id is odd\n");
} else {
printf("%d\n", getpid());
printf("its even two childs were created\n");
int i = fork();
if (i == 0) {
printf("child 1 chiled id is %d, parent is %d\n", getpid(),
getppid());
} else {
int i2 = fork();
if (i2 == 0) {
printf("child 2 chiled id is %d, parent is %d\n", getpid(),
getppid());
}
}
}
}
the parent id is 6560
6560
its even two childs were created
child 2 chiled id is 6562, parent is 707
child 1 chiled id is 6561, parent is 707
答:
2赞
Oka
11/12/2023
#1
您的父进程不会等待其子进程,并且很可能在它们有机会调用 之前终止。当父进程在其子进程之前终止时,子进程将成为孤立进程。getppid
在 Linux 中,孤立进程要么被重新命名为进程 (PID 1),要么被最近的祖先子收割者进程,后者在子进程终止时执行收割子进程的必要任务。在您的机器上似乎正在使用一个收割者,这是 返回的 ID。init
getppid
(参见 prctl(2),
PR_SET_CHILD_SUBREAPER
/ PR_GET_CHILD_SUBREAPER
。
(命令 ps -p 707
还将提供有关充当收割者的进程的信息。)
你需要一个像这样的结构
while (wait(NULL) > 0)
/* very basic example */;
以正确等待和收获子进程。
评论