Linux使用信号机制实现sleep函数功能

#include
#include
#include
#include
#include
void Catch (int signo)
{
     

}
unsigned int MySleep(unsigned int seconds)
{
     
    //设置捕捉函数
    struct sigaction newact, oldcat;
    newact.sa_handler = Catch;
    sigemptyset(&newact.sa_mask);
    newact.sa_flags = 0;
    int ret= sigaction(SIGALRM, &newact, &oldcat);
    if (ret == -1)
    {
     
        perror("sigcation error");
        exit(-1);
    }
    //设置屏蔽信号集
    sigset_t mask, oldmask,suspmask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGALRM);
    sigprocmask(SIG_BLOCK, &mask, &oldmask);

    suspmask = oldmask;
    sigdelset(&suspmask, SIGALRM);

    alarm(seconds);
  // ret= pause();//被捕捉的信号才被唤醒
    sigsuspend(&suspmask);


   if (ret == -1 && errno == EINTR)
   {
     
       printf("pause success\n");
   }
   ret=alarm(0);
   sigaction(SIGALRM, &oldcat,NULL);//恢复SIGALRM原有处理方式
   sigprocmask(SIG_SETMASK, &oldmask,NULL);
   return ret;
}

int main()
{
     
    while (true)
    {
     
        MySleep(3);
        printf("---------\n");
    }
   
    return 0;
}

你可能感兴趣的:(linux)