#include<stdio.h> #include<unistd.h> #include<signal.h> void handle(); void waiting(); int wait_mark; int main() { int p1; while((p1=fork())==-1); if(p1>0) { int sonid; printf("================= father: %d============== \n",getpid() ); wait_mark=1; printf("fater waiting...\n"); signal(SIGINT,handle); waiting(); //等待,ctrl+c之后便可退出 kill(p1,16); printf("wait return value: %d\n",wait(0) ); printf("================= father end ============= \n",getpid() ); exit(0); } else { printf("================= son %d================== \n",getpid() ); printf("p1: %d\n",p1); signal(16,handle); wait_mark=1; printf("son waiting...\n"); waiting(); //等待,父进程发送中断信号16 便可退出,好像这里出问题了 printf("son is killed by father\n"); exit(0); } } void handle() { wait_mark=0; } void waiting() { while(wait_mark==1); }
程序目的:父进程接受Ctrl+c,发送中断信号,终止子进程
但是 输出son is killed by father没有执行!为什么? Ctrl+c发送中断信号不止发送给了父进程也发给了子进程,子进程在处理16信号之前就被结束了
因为ctrl+c杀向进程组, 于是子进程被SIGINT灭了。 在子进程中注册SIGINT的处理函数,处理函数中什么都不做