Example of alarm function in linux
- 2021-01-19 22:35:10
- OfStack
linux Introduction to alarm functions
The code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
int main(int argc, char *argv[])
{
alarm(5);
sleep(20);
printf("end!\n");
return 0;
}
After 5 seconds of running, the kernel fires to the process
SIGALRM
Message, the process was terminated, so the result of the above procedure is:
Alarm clock
]Of course, we can also define the signal handler function artificially, as follows:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
void sig_alarm(int sig)
{
printf("sig is %d, sig_alarm is called\n", sig);
}
int main(int argc, char *argv[])
{
signal(SIGALRM, sig_alarm); // registered alarm The function that corresponds to the signal
alarm(5); // 5 Seconds later, the kernel emits to the process alarm Signal, Execute the corresponding signal registration function
sleep(20);
printf("end!\n");
return 0;
}
Results:
[
sig is 14, sig_alarm is called
end!
As you can see, instead of killing the process, the kernel sends the SIGALRM signal to the application process and performs the corresponding registration function.
That's easy. So much for that.
conclusion