hi programmers!)
Please help me understand this -
as I understand from practice - the getting SIGALRM by process is ends the process - but I can't find the explanation of this guess.
for exp. -
I have code -

int main(void)
{
/* Установить будильник */
sleep(1);
if((alarm(5)) > 0)
printf("an alarm was already set"); else puts("know we've set the alarm - there wasn't any before.");

sleep(30);
puts("how did we get here?");
exit(EXIT_FAILURE);
}

we'll never see the message

how did we get here?

but whY?
thanks in advance)

Dani AI

Generated

As pointed out, the behaviour in 's program comes from the signal machinery: alarm(5) schedules delivery of SIGALRM, and with no user handler installed the process is taken down by the signal's default action. The visible effect is that the sleep(30) never completes and the final puts is never reached.

A few practical details that clarify the observation: alarm() schedules SIGALRM and returns any remaining seconds from a previously set alarm (). The kernel will either run a registered handler, ignore the signal, or perform the default action; default actions for signals are summarized in signal(7). For reliable, portable handlers prefer sigaction(2) over the legacy signal() wrapper (sigaction(2)). Also note that system calls such as sleep() are interrupted by signals.

Minimal safe pattern to catch SIGALRM:

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

volatile sig_atomic_t alarmed = 0;

static void on_alarm(int sig) {
    alarmed = 1;                /* set a flag (async-signal-safe) */
    write(STDOUT_FILENO, "alarm\n", 6);
}

int main(void) {
    struct sigaction sa = {0};
    sa.sa_handler = on_alarm;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;            /* or SA_RESTART as needed */
    if (sigaction(SIGALRM, &sa, NULL) == -1) perror("sigaction");
    alarm(5);
    while (!alarmed) pause();
    puts("continued after alarm");
    return 0;
}

Keep handlers tiny and only use async-signal-safe functions inside them (see signal-safety(7)). For robustness prefer sigaction, use a volatile sig_atomic_t flag to communicate with main code, and consider SA_RESTART if interrupted syscalls should resume.

Recommended Answers

All 2 Replies

Each signal has an associated default handler (or action). In the case of SIGALRM that action is to terminate the process. You can change this default action (for most signals) by registering a signal handler of your own or assigning SIG_IGN (ignore).

commented: +++++++++ +3

thanks you, L7Sqr)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.