linux获取父进程id和名字,linux – 输出中的意外父进程id

我的代码是分支进程并打印每个进程的PID和PPID.我期待孩子的PPID与父母的PID相同,但它不是这样的.

我正在使用Ubuntu 14.04.

#include

#include

int main(){

int pid;

pid = fork();

if(pid==0){

printf("\nI am the child and my parent id is %d and my id %d\n", getppid(), getpid());

}

else

printf("\nI am the parent and my pid is %d and my parent id is %d\n", getpid(), getppid());

return 0;

}

这是我得到的输出:

I am the parent and my pid is 29229 and my parent id is 27087

I am the child and my parent id is 1135 and my id is 29230

解决方法:

我的猜测是:父母在孩子面前回来,后来变成了一个孤儿. PID 1135必须是您的用户初始化进程,该进程成为进程的新父进程. (Ubuntu用户会话中有2个subreapers).

$ps -ef | grep init

you 1135 ... init --user

如果您希望您的父母等待其孩子,请使用等待.你实际上已经有了包括:

#include

#include

int main(){

int pid;

pid = fork();

if(pid == 0)

printf("\nI am the child and my parent id is - %d and mine id %d\n",getppid(),getpid());

else{

printf("\nI am the parent and my pid is %d and my parent id is %d\n",getpid(),getppid());

wait(NULL);

}

return 0;

}

这将确保父级不会在子级的printf之前退出.您可以通过在此处插入一些sleep()调用来更清楚地看到此行为,以查看事件发生的顺序.

有关subreapers的更多信息,请参见have a look here.

标签:linux,ubuntu,system-calls,fork

来源: https://codeday.me/bug/20190814/1653651.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值