Linux信号——Sleep函数的模拟实现(利用alarm,pause,sigsuspend函数)

mysleep——利用alarm pause函数实现版本

#include
#include
#include

void sig_alrm(int signo)
{}

int mysleep(int second)
{
    struct sigaction new,old;
    int unslept = 0;
    new.sa_handler = sig_alrm;
    sigemptyset(&new.sa_mask);
    new.sa_flags = 0;
    sigaction(SIGALRM,&new,&old);
    alarm(second);
    pause();
    unslept = alarm(0);
    sigaction(SIGALRM,&old,NULL);
    return unslept;

}

int main()
{
    while(1)
    {
        mysleep(3);
        printf("I have wait 3 second...\n");
    }
    return 0;
}

mysleep——利用sigsuspend函数实现

#include
#include
#include

void sig_alrm(int signo)
{}

int mysleep(int second)
{
    struct sigaction oldact,newact;
    sigset_t newmask,oldmask,susmask;
    int unslept;

    newact.sa_handler = sig_alrm;

    sigemptyset(&newact.sa_mask);
    newact.sa_flags = 0;
    sigaction(SIGALRM,&newact,&oldact);

    sigemptyset(&newmask);
    sigaddset(&newmask,SIGALRM);
    sigprocmask(SIG_BLOCK,&newmask,&oldmask);

    alarm(second);

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

    sigsuspend(&susmask);

    unslept = alarm(0);
    sigaction(SIGALRM,&oldact,NULL);

    sigprocmask(SIG_SETMASK,&oldmask,NULL);
    return unslept;
}
int main()
{
    while(1)
    {
        mysleep(3);
        printf("I have waited 3 second\n");
    }
    return 0;
}

你可能感兴趣的:(linux)