#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
static void
sig_alrm(int signo)
{
/* nothing to do, just return to wake up the pause */
}
//使用 alarm 实现精确到秒的sleep,单位秒
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()
{
printf("start sleep1\n");
system("date");
sleep1(3);
printf("end\n");
system("date");
return 0;
}
#include <setjmp.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
static jmp_buf env_alrm;
static void
sig_alrm(int signo)
{
longjmp(env_alrm, 1);
}
//使用setjmp 实现精确到秒的sleep,单位秒
unsigned int sleep2(unsigned int seconds)
{
if (signal(SIGALRM, sig_alrm) == SIG_ERR)
return(seconds);
if (setjmp(env_alrm) == 0) {
alarm(seconds); /* start the timer */
pause(); /* next caught signal wakes us up */
}
return(alarm(0)); /* turn off timer, return unslept time */
}
int main()
{
printf("start sleep2\n");
system("date");
sleep2(3);
printf("end\n");
system("date");
return 0;
}