这是我的代码,为了执行这个程序,我运行 ./2c 10 5
—
参数 1 为 10,参数 2 为 5。该程序将运行 10 个子进程,第 5 个子进程将生成另一个子进程,但在这种情况下,我的 ppid 始终相同。它永远不会改变。所以对于每个 child ,我得到了相同的 ppid,
我得到的输出是:
pid: 1 ppid: 6 pid: 2 ppid: 6 pid: 3 ppid: 6 pid: 4 ppid: 6 pid: 5 ppid: 6`` pid: 6 ppid: 6 pid: 7 ppid: 6 pid: 8 ppid: 6 pid: 9 ppid: 6 pid: 10 ppid: 6
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[],char *envp[])
{
int i,a;
a=getpid();
int pid;
int child,child2;
child=atoi(argv[1]);
child2=atoi(argv[2]);
if(atoi(argv[2])>atoi(argv[1]))
{
printf("arg2 is bigger than arg1!");
exit(1);
}
for(i=1;i<=child;i++)
{
pid=fork();
if(i=child2 && pid==0)
{
pid=fork();
break;
}
if(pid==0)
break;
}
if(getpid()!=a)
if(getppid()==a)
{
printf("PID: %d PPID: %d\n",getpid(),getppid());
sleep(5);
exit(0);
}
for(i=1;i<=child+1;i++)
wait(0);
return 0;
}
这是我的代码有人可以测试它并在这个网站上发送输出...所以我可以比较..编译我使用 gcc test.c -o test 并运行 ./test 10 5...
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[], char *envp[])
{
int i,a;
a=getpid();
pid_t pid;
int child,child2;
child=atoi(argv[1]);
child2=atoi(argv[2]);
if(atoi(argv[2])>atoi(argv[1]))
{
printf("2nd argumentet is bigger than 1st");
exit(1);
}
for(i=1;i<=child;i++)
{
pid=fork();
if(i==child2 && pid==0)
{
pid=fork();
break;
}
if(pid==0)
break;
}
if(getpid()!=child2)
{
printf("PID: %d PPID: %d\n",getpid(),getppid());
sleep(5);
exit(0);
}
for(i=0;i<=child+1;i++)
wait(0);
return 0;
最佳答案
您的代码并未证明您声称发生了什么。您仅打印子项的输出,而不是孙项的输出,因为您使用以下行专门检查子项:
if(getppid()==a)
在该行中,a
保存程序原始实例的 pid。这不会改变,因为当您调用 fork
时,您已经传递了分配 a
的行。所有直接子级的父级 pid 始终相同,因为这就是 parent 的意思。
删除我在上面突出显示的行,您应该会看到预期的结果。
关于c - 为什么 getppid 返回相同的值,即使对于孙进程也是如此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12283200/