> if timr period is short and before function exit, another fire occurs, what would happen?.
Signals are not queued.
Generally speaking, you should not be doing a lot of work inside signal handlers.
Code:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/time.h>
// https://en.wikipedia.org/wiki/Ackermann_function#Table_of_values
// https://www.geeksforgeeks.org/ackermann-function/
int ack(int m, int n)
{
if (m == 0){
return n+1;
}
else if((m > 0) && (n == 0)){
return ack(m-1, 1);
}
else if((m > 0) && (n > 0)){
return ack(m-1, ack(m, n-1));
}
}
// Only call things on this list from a signal handler
// https://man7.org/linux/man-pages/man7/signal-safety.7.html
void fire(int sig) {
static char in[] = "@-in\n";
static char out[] = "@-out\n";
write(1,in,strlen(in));
if ( ++in[0] > '~' ) in[0] = '@';
// Uncomment the next line to cause many events to be missed.
//ack(3,11); // burn way too much time in signal handler
write(1,out,strlen(out));
if ( ++out[0] > '~' ) out[0] = '@';
}
int main ( ) {
signal(SIGALRM,fire);
struct itimerval t;
t.it_interval.tv_sec=0;
t.it_interval.tv_usec=500000;
t.it_value = t.it_interval;
raise(SIGALRM);
setitimer(ITIMER_REAL, &t, NULL);
printf("Ack(3,11)=%d\n",ack(3,11));
printf("Ack(4,1)=%d\n",ack(4,1));
unsigned int u = sleep(5);
printf("Sleep returned %u\n", u);
return 0;
}
Uncomment line 30 for a totally different experience.
> how to stop a timer immediately?. How to restart the timer after stopping?.
> how to delete a timer?. How to restart the timer after deleting?.
The manual page has all these answers.
getitimer(3p) - Linux manual page