函数pause
调用该函数可以造成进程主动挂起,等待信号唤醒,调用该系统调用的进程处于阻塞状态(主动放弃CPU)直到有信号递达将其唤醒。
- 将进程置为可中断睡眠状态。然后 它调用schedule(),使linux进程调度器找到另一个进程来运行。
- pause使调用者进程挂起,直到一个信号被捕捉。
pause() return only when a signal was caught and signal-catching function returned, In this case pause() return -1, and errno is set to EINTR.
1. pause函数原型:
#include<unistd.h>
int pause(void);
返回值:-1; errno设置为EINTR
返回值:
- 如果信号的默认处理动作是终止进程,则进程终止,pause函数没有机会返回。
- 如果信号的默认动作是忽略,进程继续处于挂起状态,pause函数不返回
- 如果信号的处理动作是捕捉,则【调用完信号处理函数之后,pause返回-1】errno设置为EINTR,表示“被信号中断”
- pause收到的信号不能屏蔽,如果被屏蔽,那么pause就不能被唤醒。
1. 测试代码
#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);//恢复AIGALRM信号旧有的处理方式
return ret;
}
int main()
{
while(1)
{
mysleep(3);
printf("----------------------------\n");
}
return 0;
}
输出结果:
2. 测试代码:
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
void handler(int sig);
int main(int argc, char *argv[])
{
if(signal(SIGINT, handler) == SIG_ERR) {
perror("signal error");
exit(1);
}
for(; ;) {
pause();
printf("pause return\n");
}
return 0;
}
void handler(int sig)
{
printf("recv a sig = %d\n", sig);
}
输出结果: