futurezone 2010-12-31
alarm信号定时运行程序 Linux
#include <stdio.h>
#include <signal.h>
void sigprint(int n)
{
printf("2 seconds past.\n");
int i ;
for(i = 0;i<1000;i++)
for(i = 0;i<1000;i++)
for(i = 0;i<1000;i++)
for(i = 0;i<1000;i++)
;
}
int mysleep(int nsec)
{
int unleft;
sigset_t newmask,oldmask,susmask;
struct sigaction newact,oldact;
newact.sa_handler = sigprint;
sigemptyset(&newact.sa_mask);
newact.sa_flags = 0;
sigaction(SIGALRM,&newact,&oldact);
sigemptyset(&newmask);
sigaddset(&newmask,SIGALRM);
sigprocmask(SIG_BLOCK,&newmask,&oldmask);
alarm(nsec);
susmask = oldmask;
sigdelset(&susmask,SIGALRM);
sigsuspend(&susmask);
unleft = alarm(0);
sigaction(SIGALRM,&oldact,NULL);
sigprocmask(SIGALRM,&oldmask,NULL);
return unleft ;
}
int main(void)
{
int i = 10;
while(i){
mysleep(2);
i--;
}
return 0;
}