信号 09 | 函数pause

函数pause

调用该函数可以造成进程主动挂起,等待信号唤醒,调用该系统调用的进程处于阻塞状态(主动放弃CPU)直到有信号递达将其唤醒。

#include<unistd.h>
int pause(void);
 
                                                   返回值:-1; errno设置为EINTR

返回值:

  • 如果信号的默认处理动作是终止进程,则进程终止,pause函数没有机会返回。
  • 如果信号的默认动作是忽略,进程继续处于挂起状态,pause函数不返回
  • 如果信号的处理动作是捕捉,则【调用完信号处理函数之后,pause返回-1】errno设置为EINTR,表示“被信号中断”
  • pause收到的信号不能屏蔽,如果被屏蔽,那么pause就不能被唤醒。

测试代码

#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<errno.h>
#include<unistd.h>

void catch_sigalrm(int signo)
{
    ;
}

unsigned int mysleep(unsigned int seconds)
{
    int ret;
    struct sigaction act, oldact;
    act.sa_handler = catch_sigalrm;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;

    ret = sigaction(SIGALRM, &act, &oldact);
    if(ret == -1) {
        perror("sigaction error");
        exit(1);
    }

    alarm(seconds);
    ret = pause();
    if(ret == -1 && errno == EINTR) {
        printf("pause sucess\n");
    }

    ret = alarm(0);
    sigaction(SIGALRM, &oldact, NULL);
    
    return ret;
}

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

输出结果:

猜你喜欢

转载自blog.csdn.net/isunbin/article/details/83090756