为什么prctl没有如小弟我所预期的设置一个父进程退出发给子进程信号
为什么prctl没有如我所预期的设置一个父进程退出发给子进程信号?
我写了一个小程序,在fork出的子进程中使用prctl,设置父进程退出后自动发送给子进程退出信号。
我预期的是,我运行程序以后,父进程和子进程都在getchar()阻塞。
我用ps看到父子两个进程
然后我杀死父进程(kill -9),我期待的是,子进程可以自动退出,因为子进程已经调用过prctl,能接收到父进程的通知对吧?
但是实际运行的结果,如上所示,子进程并没有退出,而是成了孤儿进城了。这是为什么呢?
为什么父进程退出以后,系统没有能通知子进程父进程已经退出了,然后子进程也退出?
可能我的程序或者理解有问题,还请高人指正,多谢!
------解决思路----------------------
程序有错误,父进程调用fork返回pid!=0,子进程返回0,因为子进程可以getppid得到父进程id,不需要依赖从fork返回的id
还有就是prctl的第二个参数必须是SIGKILL。
我写了一个小程序,在fork出的子进程中使用prctl,设置父进程退出后自动发送给子进程退出信号。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#include<sys/prctl.h>
int main()
{
pid_t p = fork();
if(p==0)//father
{
printf("father\n");
getchar();
return 0;
}
else if(p<0)
exit(1);
printf("child\n");
prctl(PR_SET_PDEATHSIG,0,0,0,0);
getchar();
return 0;
}
我预期的是,我运行程序以后,父进程和子进程都在getchar()阻塞。
我用ps看到父子两个进程
[a@localhost ~]$ ps -ef|grep a.out
a 13238 2727 0 02:41 pts/1 00:00:00 ./a.out
a 13239 13238 0 02:41 pts/1 00:00:00 ./a.out
a 13255 13240 0 02:42 pts/2 00:00:00 grep a.out
[a@localhost ~]$ kill -9 13238
[a@localhost ~]$ ps -ef|grep a.out
a 13239 1 0 02:41 pts/1 00:00:00 ./a.out
a 13257 13240 0 02:42 pts/2 00:00:00 grep a.out
然后我杀死父进程(kill -9),我期待的是,子进程可以自动退出,因为子进程已经调用过prctl,能接收到父进程的通知对吧?
但是实际运行的结果,如上所示,子进程并没有退出,而是成了孤儿进城了。这是为什么呢?
为什么父进程退出以后,系统没有能通知子进程父进程已经退出了,然后子进程也退出?
可能我的程序或者理解有问题,还请高人指正,多谢!
------解决思路----------------------
程序有错误,父进程调用fork返回pid!=0,子进程返回0,因为子进程可以getppid得到父进程id,不需要依赖从fork返回的id
还有就是prctl的第二个参数必须是SIGKILL。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#include<sys/prctl.h>
int main()
{
pid_t p = fork();
if(p>0)//father
{
printf("father\n");
getchar();
return 0;
}
else if(p<0)
exit(1);
printf("child\n");
prctl(PR_SET_PDEATHSIG,SIGKILL);
getchar();
return 0;
}