学习进程间通信时,知道了子进程退出 exit(0)后,会发一个信号
SIG_CHID 通知父进程。为了确保子进程退出后,不会变成僵尸进程 Z,父进程应该用 wait或者waitpid来接收下子进程发过来的该信号。
比如代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
void myfunc(int signum)
{
int i;
i = 0;
while (i < 2)
{
printf("process things signum %d\n", signum); //10
sleep(1);
i++;
}
return; //返回 main 函数
}
void myfunc1(int signum)
{
printf("receive %d\n", signum);
wait(NULL);
return; //返回 main 函数
}
int main()
{
int status = 0;
pid_t pid;
pid = fork(); //while((p1=fork( ))==-1); /*创建子进程p1*/
if (pid > 0)
{
//wait(NULL);如果想在这里回收子进程会, 父进程会在这里产生阻塞
signal(10, myfunc); //14就是alarm信号
signal(17, myfunc1); //17就是exit里面的child信号
while (1)
{
sleep(1);
printf("I am father\n");
}
}
if (pid == 0)
{
sleep(4);
kill(getppid(), 10); //用户自定义信号 10
sleep(5);
exit(0); //里面包括了发送给父进程的kill(getppid(), SIG_CHLD) 17
}
return 0;
}
BUT!我弄了半天一直收不到 17号进程!查看过头文件是否引用到,代码是否拼写错....3 hours later....😢 😭
我把代码发给另一个人帮我试试,别人没改代码,直接运行,就收到 17号 信号!
于是我猜别人是Windows里面用虚拟机运行的纯Linux系统可以,我MacOS不行。然后再次比对发现:
Windows 电脑上
Mac电脑上,仔细数数,CHID 在 20 号!!!!💥 🤢 ☠️
所以,只用把上述代码17,改成 20,就成功收到了子进程传过来的信号 📶 。