c – sigtimedwait()在超时前返回EAGAIN

我正在尝试学习如何使用sigtimedwait(),但我发现它并没有等待超时完成.下面它似乎比它应该更快地返回EAGAIN 4s(每1分钟超时1秒):

#include <signal.h>
#include <syslog.h>
#include <stdarg.h>
#include <stddef.h>
#include <errno.h>


int main(int argc, char* argv[]) {
    setlogmask(LOG_UPTO(LOG_NOTICE));
    openlog ("SIG_TIMED_WAITER", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
    syslog (LOG_NOTICE, "Started");

    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGUSR1);

    struct timespec to;
    to.tv_sec = 240;
    to.tv_nsec = 0;

    int ret = sigtimedwait(&set, NULL, &to);
    if(ret < 0) {
        if (errno == EAGAIN) {
            syslog (LOG_NOTICE, "EAGAIN: TimedWait complete...");
        } else {
            syslog (LOG_NOTICE, "ERROR!");
        }
    }   else {
        syslog (LOG_NOTICE, "Interrupted by signum: %d.", ret);
    }

    syslog (LOG_NOTICE, "Terminated.");
    closelog();
}

这是输出:

$tail -f /var/log/syslog|grep "SIG_TIMED_WAITER"
Jan  7 15:39:41 localhost SIG_TIMED_WAITER[13275]: Started
Jan  7 15:43:36 localhost SIG_TIMED_WAITER[13275]: EAGAIN: TimedWait complete...
Jan  7 15:43:36 localhost SIG_TIMED_WAITER[13275]: Terminated.

我原本预计会在4秒后看到“EAGAIN:TimedWait complete …”.

我的代码有问题,还是由于其他原因?请注意,我没有看到这个,例如,等待四分钟的select().

最佳答案 LOG_LOCAL1是保留项目. I.E.不要使用它

而是使用LOG_USER

如果options参数也具有LOG_PERROR,则更容易遵循操作

然后输出也将记录在stderr上.

这是该程序的更正/工作版本.

#define _GNU_SOURCE

#include <signal.h>
#include <syslog.h>
#include <stdarg.h>
#include <stddef.h>
#include <errno.h>


int main( void )
{
    setlogmask(LOG_UPTO(LOG_NOTICE));
    openlog ("SIG_TIMED_WAITER", LOG_CONS | LOG_PID | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);
    syslog (LOG_NOTICE, "Started");

    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGUSR1);

    struct timespec to;
    to.tv_sec = 240;
    to.tv_nsec = 0;

    int ret = sigtimedwait(&set, NULL, &to);
    if(ret < 0)
    {
        if (errno == EAGAIN)
        {
            syslog (LOG_NOTICE, "EAGAIN: TimedWait complete...");
        }

        else
        {
            syslog (LOG_NOTICE, "ERROR!");
        }
    }

    else
    {
        syslog (LOG_NOTICE, "Interrupted by signum: %d.", ret);
    }

    syslog (LOG_NOTICE, "Terminated.");
    closelog();

    return 0;
} // end function: main

我正在运行ubuntu linux 14.04

(在这种情况下,15212是运行程序的控制台/终端的PID.)

从控制台/终端(从stderr输出)

SIG_TIMED_WAITER[15212]: Started
SIG_TIMED_WAITER[15212]: EAGAIN: TimedWait complete...
SIG_TIMED_WAITER[15212]: Terminated.

来自/ var / log / syslog:

Jan  7 05:50:07 rkwill-desktop SIG_TIMED_WAITER[15212]: Started
Jan  7 05:54:07 rkwill-desktop SIG_TIMED_WAITER[15212]: EAGAIN: TimedWait complete...
Jan  7 05:54:07 rkwill-desktop SIG_TIMED_WAITER[15212]: Terminated.

注意:初始输出和EAGAIN输出之间的时间是4分钟(240秒)

点赞