最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c - Semaphore incrementation from inside SIGINT handler produces weird behavior - Stack Overflow

programmeradmin0浏览0评论

I am trying to set up SIGINT signal handler to wake up the main thread via binary semaphore. For that, as I attach below, I set up a SIGINT handler to run handler() function which just increments semaphore. Meanwhile, in the main thread just sem_wait(&mutex) is called in the infinite loop and then it just gets the semaphore value and prints it.

The way of waiting for a semaphore I did is while (sem_wait(&mutex)); because apparently every time Ctrl+C is pressed the sem_wait() returns with EINTR error. I did not expect it to be that way as I thought it behaves as true passive waiting with suspension of the process.

I feel that using sem_post() from inside signal handlers should be fine as that is a async-signal-safe function. But shouldn't there be more elegant design choices to do what I want to do? i.e. put a thread to passive wait and then wake it up from the signal handler. I would be grateful for any advice.

The code:

sem_t mutex;

static void handler (int num) {
    sem_post(&mutex);
}
 
int main() {
    struct sigaction sa;

    sa.sa_handler = handler;
    sa.sa_flags = 0;
    if (sigemptyset(&sa.sa_mask) == -1) {
        perror("sigemptyset failed");
        return EXIT_FAILURE;
    }

    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("sigaction failed");
        return EXIT_FAILURE;
    }

    sem_init(&mutex, 0, 0);

    int sval;

    printf ("Get ready, press Ctrl+C...\n");

    while (1) {
        while (sem_wait(&mutex))
            printf ("%s\n", strerror(errno));

        sem_getvalue(&mutex, &sval);
        printf("sem is %d\n", sval);
    }

    printf("Bye");
}
发布评论

评论列表(0)

  1. 暂无评论