无限循环 - 等待SIGRTMIN

时间:2014-06-10 15:34:11

标签: c signals handler

我试图使用信号SIGRTMIN,以便在允许的情况下使用do_stuff。这是我第一次使用信号。问题是我陷入了

while (go == 0){printf("Waiting\n");}

这是我的代码:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

volatile sig_atomic_t go = 0;

void handler (int sig)
{   
    go = 1;
    signal (sig, handler);
}

void do_stuff (void)
{
    puts ("Doing stuff while waiting for alarm....");
}

int main (void)
{
    int i=0;

    signal (SIGRTMIN, handler);

    while(i<5){
        while (go == 0){printf("Waiting\n");}
        do_stuff();
        i++;
    }

    return EXIT_SUCCESS;
}
你能帮忙吗?提前谢谢!

1 个答案:

答案 0 :(得分:2)

您需要从某处发送SIGRTMIN信号;在发送之前它不会响应信号。最简单的方法是让它自己发送信号,所以这里是你的代码的温和修订版本。

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

#ifndef SIGRTMIN
#define SIGRTMIN SIGUSR1
#endif

volatile sig_atomic_t go = 0;

static
void handler(int sig)
{
    go = 1;
    signal(sig, handler);
}

static
void do_stuff(void)
{
    puts("Doing stuff while waiting for alarm....");
    go = 0;
}

int main(void)
{
    signal(SIGRTMIN, handler);

    for (int i = 0; i < 5; i++)
    {
        while (go == 0)
        {
            puts("Waiting...");
            struct timespec t = { .tv_sec = 0, .tv_nsec = 300000000 };
            nanosleep(&t, 0); 
            kill(getpid(), SIGRTMIN);
        }
        do_stuff();
    }

    return EXIT_SUCCESS;
}

示例运行:

Waiting...
Doing stuff while waiting for alarm....
Waiting...
Doing stuff while waiting for alarm....
Waiting...
Doing stuff while waiting for alarm....
Waiting...
Doing stuff while waiting for alarm....
Waiting...
Doing stuff while waiting for alarm....

输出不是很令人兴奋,但它至少有效。 nanosleep()睡眠时间为0.3秒。