【问题标题】:Simple pthreads and signal program on linux wont runlinux上的简单pthreads和信号程序不会运行
【发布时间】:2013-10-17 01:48:05
【问题描述】:

这个程序应该是

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

我的代码编译得很好,当我运行它时,绝对没有任何反应,甚至没有我放在那里作为测试的第一个 printf。看了一个小时都没报错,为什么不运行呢?

编辑:现在运行,感谢 charlie,但是当它创建线程时,它输出“[thread] sleep for 1 m[thread] sleep for 1 minute”然后结束,它从不等待第二个信号

#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”
  • stdio 被缓冲,这意味着发送到 stdout 的字符在看到换行符之前不会被刷新。试试看,改 printf("hello");到 printf("你好\n");你会看到的。我运行了你的代码,它可以工作。
  • 天哪,非常感谢。一定要喜欢那些奇怪的小东西
  • 新的奇怪问题,线程创建后退出进程,从不等待USR2信号

标签: c linux pthreads signals


【解决方案1】:

在所有 printf 中添加一个换行符“\n”。没有它,stdout 将不会刷新,即使它是,它也会显示您的程序无法运行。

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

【讨论】:

    【解决方案2】:

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

    void handle_USR1(int x) { int s; printf("[signal] creating the thread\n"); s = pthread_create(&thread, NULL, &temp, NULL); pthread_join(thread, NULL); }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 2013-07-30
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多