C linux上的简单pthreads和signal程序无法运行

C linux上的简单pthreads和signal程序无法运行,c,linux,pthreads,signals,C,Linux,Pthreads,Signals,这个节目应该是 父级只是无限期地等待任何子级返回(提示,waitpid)。 B孩子设置了两个信号处理程序(提示、信号),然后进入睡眠状态5分钟。 我第一个信号处理程序侦听USR1信号,并在接收到该信号时: 1.创建一个线程(提示,pthread_create)。 A.基本上,线程需要做的就是“打招呼”并睡60分钟 秒。 二,。第二个信号处理程序监听USR2信号,并在接收到该信号后: 1.销毁线程(提示,pthread\u destroy) 我的代码编译得很好,就在我运行它的时候,绝对没有发生任何

这个节目应该是

父级只是无限期地等待任何子级返回(提示,waitpid)。 B孩子设置了两个信号处理程序(提示、信号),然后进入睡眠状态5分钟。 我第一个信号处理程序侦听USR1信号,并在接收到该信号时: 1.创建一个线程(提示,pthread_create)。 A.基本上,线程需要做的就是“打招呼”并睡60分钟 秒。 二,。第二个信号处理程序监听USR2信号,并在接收到该信号后: 1.销毁线程(提示,pthread\u destroy)

我的代码编译得很好,就在我运行它的时候,绝对没有发生任何事情,甚至连我作为测试放在那里的第一个printf都没有发生。我已经盯着它看了一个小时了,没有任何错误,所以为什么不运行呢

编辑:现在运行,谢谢charlie,但是当它创建线程时,它会输出“[thread]休眠1分钟[thread]休眠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);
}
#包括
#包括
#包括
#包括
#包括
#包括
pthread\u t线程;
void*temp()
{
printf(“[thread]hello professor\n”);
printf(“[thread]休眠1分钟\n”);
睡眠(60);
}
无效句柄_USR1(int x)
{
int-s;
printf(“[signal]创建线程\n”);
s=pthread_create(&thread,NULL,&temp,NULL);
}
无效句柄_USR2(int x)
{
int-s;
printf(“[signal]正在销毁线程\n”);
s=pthread_cancel(线程);
}
内部主(空)
{
int status=0;
如果(fork()!=0)
{
printf(“[parent]正在等待…”\n”);
waitpid(-1,状态为0(&S);
}
其他的
{
printf(“[child]创建线程:kill-USR1%d\n”,getpid());
printf(“[child]结束线程:kill-USR2%d\n”,getpid());
printf(“[child]设置信号处理程序\n”);
信号(SIGUSR1,手柄\ USR1);
信号(SIGUSR2,手柄\ USR2);
printf(“[child]等待信号\n”);
睡眠(300);
}
返回(0);
}
在所有printf中添加换行“\n”。如果没有它,stdout将不会刷新,并且它将显示您的程序不工作,即使它是


另外,检查fork()是否失败也是一个好主意。fork()在失败时返回-1并设置errno。

我在搜索其他内容时遇到了这个问题,并意识到一旦处理了SIGUSR1信号,程序就会终止。您需要通过发出pthread_join来等待线程,就像等待子进程一样


无效句柄_USR1(int x)
{
int-s;
printf(“[signal]创建线程\n”);
s=pthread_create(&thread,NULL,&temp,NULL);
pthread_join(线程,NULL);
}

在初始printf中添加一个换行符以使其对齐。或者打电话给福鲁斯。事实上,在所有printf中添加一个换行符可能会让您相信它确实有效。另外,检查fork()中的-1也是一个好主意。@charlie添加换行符会做什么?它甚至从不打印stdio缓冲的第一个“hello”,这意味着发送到stdout的字符在看到换行符之前不会被刷新。试试看,只要改变printf(“你好”);到printf(“hello\n”);你会看到的。我运行了你的代码,很有效。天哪,非常感谢你。我喜欢这个奇怪的小东西新的奇怪问题tho,它在线程创建后退出进程,从不等待USR2信号