这个程序应该是pthreads和信号处理C早期结束
家长只是无限期地等待任何孩子返回(提示,waitpid)。 b。孩子设置了两个信号处理程序(提示,信号)并进入睡眠5分钟。 i。第一个信号处理程序侦听USR1信号,并在收到它之后: 1.创建一个线程(提示,pthread_create)。 a。基本上,线程需要做的就是“打个招呼”,然后睡60秒钟。二,第二个信号处理程序监听USR2信号,并在收到它之后: 1.销毁线程(提示,pthread_cancel)。
当此程序接收第一信号以产生该线程,它输出 “[线程]睡眠1 M [线程]睡眠1分钟” 然后结束,它永远不会等待第二信号,什么是我做错了?
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
pthread_t thread;
void* temp()
{
printf("[thread] hello professor\n");
printf("[thread] sleeping for 1 minute\n");
sleep(60);
}
void handle_USR1(int x)
{
int s;
printf("[signal] creating the thread\n");
s = pthread_create(&thread, NULL, &temp, NULL);
}
void handle_USR2(int x)
{
int s;
printf("[signal] destroying the thread\n");
s = pthread_cancel(thread);
}
int main(void)
{
int status = 0;
if(fork() != 0)
{
printf("[parent] waiting.....\n");
waitpid(-1, &status, 0);
}
else
{
printf("[child] to create the thread: kill -USR1 %d\n", getpid());
printf("[child] to end the thread: kill -USR2 %d\n", getpid());
printf("[child] setting up signal handlers\n");
signal(SIGUSR1, handle_USR1);
signal(SIGUSR2, handle_USR2);
printf("[child] waiting for signals\n");
sleep(300);
}
return (0);
}
OP的问题是,向子进程发送kill SIGUSR1会调用处理程序,然后杀死子进程,以便父进程中的waitpid()返回。问题是OP如何防止waitpid()在SIGUSR1发送给子进程后返回。 –
@charlie谢谢,我不确定到底发生了什么,仍然不知道如何修复它lol – Cyberhawk94
'pthread_create'不是一个从信号处理程序调用的安全函数,所以这看起来像是从一开始就引起麻烦。 – Duck