Alarm (time), after execution, tells the kernel to let the kernel send a timed signal to the process after a timeframe, and then the process captures the signal and processes it;
The pause () function pauses the process to give up the CPU, but the pause of the function and the sleep of the previous sleep function are interrupted sleep, which means that the interrupt signal is received and then
The statement after the pause () and sleep () functions are executed directly when the process is re-executed;
Here is an example of a timed 2-second:
/*************************************************************************> File name:alarm.c> Author: > Mail: > Created time:2015 November 20 Friday 21:12 52 seconds ****************************************************************** /#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h>void sig_ handler (int num) { printf ("Receive the Signal%d.\n", num);} int main () { signal (SIGALRM, sig_handler); Alarm (2); while (1) { pause (); printf ("Pause is over.\n"); } Exit (0);}
If we want the program to be timed every 2 seconds, this implementation is also very simple, we are in the function of processing the timing signal again 2 seconds, the example is as follows:
/*************************************************************************> File name:alarm.c> Author: > Mail: > Created time:2015 November 20 Friday 21:12 52 seconds ****************************************************************** /#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h>void sig_ handler (int num) { printf ("Receive the Signal%d.\n", num); Alarm (2);} int main () { signal (SIGALRM, sig_handler); Alarm (2); while (1) { pause (); printf ("Pause is over.\n"); } Exit (0);}
You can see that the program receives the signal 14 every 2 seconds, that is, the SIGALRM signal, and when the signal is processed, directly executes the statement below the pause () function, stating that pause () is a pause that can be interrupted;
A detailed example of alarm function and pause function in Linux