1. 程式人生 > >LINUX下模擬實現sleep函式

LINUX下模擬實現sleep函式

#include
#include
#include
void myhandler(int sig)
{}

int mysleep(int timeout)
{
     struct sigaction act,oact;
     sigset_t mask,omask,suspmask;
     unsigned int unslept;
     act.sa_handler=myhandler;
     act.sa_flags=0;
     sigemptyset(&act.sa_mask);
     sigaction(SIGALRM,&act,&oact);
     sigemptyset(&mask);
     sigaddset(&mask,SIGALRM);
     sigprocmask(SIG_BLOCK,&mask,&omask);
     alarm(timeout);
     suspmask=omask;
     sigdelset(&suspmask,SIGALRM);
     sigsuspend(&suspmask);
     int ret=alarm(0);
     sigaction(SIGALRM,&oact,NULL);
     sigprocmask(SIG_SETMASK,&omask,NULL);
     return ret;
}

int main()
 {
     while(1)
    {
        mysleep(3);
       printf("using mysleep!\n");
    }
    return 0;
 }
執行結果: