【问题标题】:Catching SIGCHLD using sigtimedwait() on BSD在 BSD 上使用 sigtimedwait() 捕获 SIGCHLD
【发布时间】:2013-06-05 10:04:18
【问题描述】:

我在使用 sigtimedwait() 来捕获 FreeBSD 上的 SIGCHLD 信号时遇到问题。以下源代码在 Debian GNU/Linux 7 上运行良好,但给了我一个在 FreeBSD 9.1 上暂时不可用的资源:

#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>

int main() {
        sigset_t set;
        pid_t pid;

        printf("SIGCHLD is %i\n", SIGCHLD);

        sigemptyset(&set);
        sigaddset(&set, SIGCHLD);
        sigprocmask(SIG_BLOCK, &set, NULL);

        pid = fork();

        if(pid == -1) {
                printf("fork failed: %s\n", strerror(errno));
                exit(1);
        } else if(pid) {
                sigset_t set2;
                siginfo_t siginfo;
                struct timespec timeout = {3, 0};
                int signal;

                sigemptyset(&set2);
                sigaddset(&set2, SIGCHLD);

                signal = sigtimedwait(&set2, &siginfo, &timeout);

                if(signal == -1) {
                        printf("sigtimedwait failed: %s\n", strerror(errno));
                        exit(2);
                } else {
                        printf("received signal %i from %i with status %i\n", signal, siginfo.si_pid, siginfo.si_status);
                }
        } else {
                sleep(1);
                exit(123);
        }

        return 0;
}

Linux 上的输出:

SIGCHLD is 17
received signal 17 from 27600 with status 123

FreeBSD 上的输出:

SIGCHLD is 20
sigtimedwait failed: Resource temporarily unavailable

在 BSD 上使用 signal() 可以正常工作,但这并不是我想要的。我错过了什么?

【问题讨论】:

    标签: c linux signals bsd sigchld


    【解决方案1】:

    我认为这是 FreeBSD 中的内核/库错误。看起来 sigtimedwait 没有报告信号,因为它默认被忽略。所以你可以做两件事

    1. 为 SIGCHLD 事件安装信号处理程序。即使由于您阻塞了信号而从未调用过它,它也可以解决该错误。

    2. 将 kqueue 与 EVFILT_SIGNAL 一起使用,这在这种情况下肯定有效,但不可移植(因此您需要 ifdef)

    对于 2,这里是等效的代码

         int kq = kqueue();
         struct kevent ke;
         EV_SET(&ke, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
         kevent(kq, &ke, 1, NULL, 0, NULL);
         if (kevent(kq, NULL, 0, &ke, 1, &timeout) == 1) {
              signal = ke.ident;
         }
         else {
             // Catches errors in the add, timeout, and kevent wait
             signal = -1;
         }
         close(kq);
         // note that siginfo is not populated, there is no way to populate it using kqueue.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 2012-06-18
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      相关资源
      最近更新 更多