The problem with the timer with a long signal handler (SIGALARM)

There is a timer that sends a SIGALARM signal every 1 second. Signal handler that sleeps. Registered 2 seconds. What's happening? In particular, I have the following code in which a process starts several threads. It's quite interesting that with this long signal handler, it looks that other threads are blocked from execution ... Can someone explain why this is so?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h> //rand
#include <sys/wait.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
#define NUM_THREADS 2

int init_timer(int real_time, int msec) {
    struct itimerval timeslice;
    timeslice.it_interval.tv_sec = msec / 1000;
    timeslice.it_interval.tv_usec = (msec % 1000) * 1000;
    timeslice.it_value.tv_sec = msec / 1000;
    timeslice.it_value.tv_usec = (msec % 1000) * 1000;
    setitimer(real_time ? ITIMER_REAL : ITIMER_VIRTUAL, &timeslice, NULL);
    return 0;
}

void install_handler(int signo, void(*handler)(int)) {
    sigset_t set;
    struct sigaction act;

    /* Setup the handler */
    act.sa_handler = handler;
    act.sa_flags = SA_RESTART;
    sigaction(signo, &act, 0);

    /* Unblock the signal */
    sigemptyset(&set);
    sigaddset(&set, signo);
    sigprocmask(SIG_UNBLOCK, &set, NULL);
    return;
}

void timerTest(int signo)
{
    printf("000\n");
    sleep(1);
    printf("111\n");
}

void * threadTest(void * threadId)
{
    while(true)
    {
        printf("222\n");
    }
}

int main(int argc, char *argv[]) {
    int real_time = 1;
    int tick_msec = 10;
    init_timer(real_time, tick_msec);
    install_handler(real_time ? SIGALRM : SIGVTALRM, &timerTest);

    pthread_t threads[NUM_THREADS];
    int rc;
    long t;
    for (t = 0; t < NUM_THREADS; t++) {
        rc = pthread_create(&threads[t], NULL, threadTest, (void *) t);
        if (rc) {
            exit(-1);
        }
    }

    void * status;
    for (t = 0; t < NUM_THREADS; t++) {
        rc = pthread_join(threads[t], &status);
        if (rc) {
            exit(-1);
        }
    }
    pthread_exit(NULL);
}

printout:

222
222
222
222
...
222
000
111
000
111
...

after the first 111 will not be 222? why is that?

+3
source share
3 answers

, (, ). , 222\n, 222\n . , , 222\n.

, printf , libc . printf " ", undefined , . , . , stdout, stdout , , "" , . stdout , rlock, - . , C, . write (2), , , undefined.

SIG_BLOCK 222\n, , 222\n , .

. , undefined.

+4

, , (, , ). . , - , , .

. sigaction SA_NODEFER .

, . (7) . " , - . POSIX " ". , undefined"

, , .    ""; coredump. -   , ,       . undefined.

.

+2

printf .

, SIGALARM, . Linux. , , . , , . , pthread_sigmask(3)

-1

All Articles