4

I'm trying to do something simple with alarms, however the printf is never executing after I do the alarm, why's that?

#include <stdio.h>
#include <signal.h> 
    int main() { 
    alarm(3); 
    printf("Hello...\n"); 
    alarm(6); 
    while(1); 
    printf("Hello2\n"); 
} 

I want hello and hello2 to be printed, only hello is being printed for now

1 Answer 1

6

You didn't specify a handler for SIGALRM, and its default behavior (per man 7 signal) is to terminate the program. Even if you did specify a handler, after it ran, you'd still be in the while(1) loop.

Here's how you'd modify your program to fix both of those problems:

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

volatile sig_atomic_t got_sigalrm = 0;

void handle_sigalrm(int signum) {
    got_sigalrm = 1;
}

int main() {
    struct sigaction act = { .sa_handler = handle_sigalrm };
    sigaction(SIGALRM, &act, NULL);
    alarm(3);
    printf("Hello...\n");
    alarm(6);
    while(!got_sigalrm);
    printf("Hello2\n");
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.