1. Alarm functions:
The alarm function sets a timer to generate a sigalrm signal when the timer times out. If this signal is not ignored or captured, its default operation is to terminate the process that calls the alarm function.
The prototype is as follows:
# Include <unistd. h>
Unsigned int alarm (unsigned int seconds );
Returns 0 or the remaining number of seconds.
Let's talk about the returned values of alarm. Each process can only have one "Alarm Clock" maintained by alarm ".
If the "Alarm Clock" times out, 0 is returned;
If another alarm function is called during the timer process, the remaining seconds of the alarm will be used as the returned value of the alarm, and the new alarm will start timing. (In fact, the new alarm replaces the previous alarm)
Code example:
# Include <unistd. h>
# Include <signal. h>
# Include <stdio. h>
/* My alarm func for print */
Static unsigned int my_alarm (unsigned int nsec)
{
Printf ("wait for % u secs to alarm", nsec );
Return alarm (nsec );
}
/* My sleep func for print */
Static unsigned int my_sleep (unsigned int nsec)
{
Printf ("sleep for % u secs", nsec );
Return sleep (nsec );
}
/* Sigalrm handler */
Static void sig_alarm (INT signo)
{
Printf ("sigalrm ");
}
Int main ()
{
/* Check alarm return value */
Unsigned int ret1, ret2;
/* Signal handle */
If (signal (sigalrm, sig_alarm) <0)
Perror ("signal ");
Printf ("Alarm start :");
/* First alarm */
Ret1 = my_alarm (5 );
My_sleep (3 );
Printf ("new alarm :");
/* Second alarm */
Ret2 = my_alarm (2 );
My_sleep (4 );
Printf ("alarm end ");
/* Show the two return values */
Printf ("First Return: % u", ret1 );
Printf ("second return: % u", ret2 );
Return 0;
}
In this Code, I encapsulated my_alarm and my_sleep, and added the printf code for tracking.
The program running result is as follows:
Alarm start:
Wait for 5 secs to alarm
Sleep for 3 secs
New alarm:
Wait for 2 secs to alarm
Sleep for 4 secs
Sigalrm
Alarm end
First Return: 0
Second return: 2
From the above results, I think I don't need to explain this program much.
The returned values of alarm are clear at a glance.
2. Pause functions:
The pause function suspends the calling process until a signal is captured. Its prototype is as follows:
# Include <unistd. h>
Int pause ();
-1 is returned, and errno is set to eintr.
This function is very simple and can be understood literally as "paused". Pause returns only when a signal processing program is executed and returned from it.