这个程序应该是简单的并行线程和信号程序不会运行
父只是无限期地等待所有子返回(提示,waitpid函数)。 b。孩子设置了两个信号处理程序(提示,信号)并进入睡眠5分钟。 i。第一个信号处理程序侦听USR1信号,并在收到它之后: 1.创建一个线程(提示,pthread_create)。 a。基本上,线程需要做的就是“打个招呼”,然后睡60秒钟。二,第二个信号处理程序监听USR2信号,并在收到之后: 1.销毁线程(提示,pthread_destroy)。
我的代码编译得很好,就在我运行它时,绝对没有任何反应,甚至没有我第一次将printf作为测试。我一直盯着它一个小时,没有错误,所以为什么不运行?
编辑︰现在运行,谢谢查理,但是当它创建线程时,它输出“[线程]睡眠1米[线程]睡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);
}
一个新行添加到最初的printf,使之冲洗等待子进程。或者打电话给fflush。事实上,为你的所有printfs添加一个换行符可能会说服你实际工作。另外,检查fork()为-1是个好主意。 –
@charlie什么会添加一个换行符呢?它甚至从不打印第一个“hello” – Cyberhawk94
stdio被缓冲,这意味着发送到stdout的字符不会被刷新,直到看到换行符。试试吧,只需更改printf(“hello”);到printf(“hello \ n”);你会看到。我运行你的代码,它的工作原理。 –