In the Chapter 10 Signals of the APUE book, there is a sample code:
#include <signal.h>
#include <unistd.h>
static void sig_alrm(int signo) {
/* nothing to do, just return to wake up the pause */
}
unsigned int sleep1(unsigned int seconds) {
if (signal(SIGALRM, sig_alrm) == SIG_ERR)
return(seconds);
alarm(seconds); /* start the timer */
pause(); /* next caught signal wakes us up */
return(alarm(0)); /* turn off timer, return unslept time */
}
int main() {
sleep1(1);
return 0;
}
which simply implement an "imcomplete" sleep().
The book says that "This function looks like the sleep function, but this simple implementation has three problems."
If the caller already has an alarm set, that alarm is erased by the first call to alarm. We can correct this by looking at alarm’s return value. If the number of seconds until some previously set alarm is less than the argument, then we should wait only until the existing alarm expires. If the previously set alarm will go off after ours, then before returning we should reset this alarm to occur at its designated time in the future.
We have modified the disposition for SIGALRM. If we’re writing a function for others to call, we should save the disposition when our function is called and restore it when we’re done. We can correct this by saving the return value from signal and resetting the disposition before our function returns.
There is a race condition between the first call to alarm and the call to pause. On a busy system, it’s possible for the alarm to go off and the signal handler to be called before we call pause. If that happens, the caller is suspended forever in the call to pause (assuming that some other signal isn’t caught).
I have some doubt about the above 3 statements:
Can somebody provide some example code for the statement1?
I don't know what the statement2 says, can someone give me robust explanation?
I don't know why statement3 will cause a race condition.
Thanks a lot!
to answer your question in the title.
The returned value is the number of seconds left in the prior call to
alarm()