文章目录
- 1.pause函数
- 1.1 pause函数例子
- 2.时序问题
- 3.解决时序问题
- 4.例子:sigsuspend函数的举例
- 5.总结
1.pause函数
1.1 pause函数例子
\qquad程序依次从1到无穷输出数字,当遇到100的整数倍时就暂停,键盘输入ctrl+c,就继续输出。
#include<stdio.h>
#include<signal.h>
#include<unistd.h>void docatch(int signo)
{printf("信号已被捕捉\n");
}int main()
{int i;signal(SIGINT,docatch);for(i=0; ;i++){if(i%100==0){pause();}else{printf("%d\n",i);}}return 0;
}
2.时序问题
3.解决时序问题
4.例子:sigsuspend函数的举例
\qquad使用alarm函数和sigsuspend函数实现sleep函数功能
#include<stdio.h>
#include<stdlib.h>
#include<error.h>
#include<unistd.h>
#include<signal.h>void catch_sigalrm(int signo)
{;
}unsigned int mysleep(unsigned int seconds)
{struct sigaction newact,oldact;sigset_t newmask,oldmask,suspmask;unsigned int unslept;newact.sa_handler = catch_sigalrm;sigemptyset(&newact.sa_mask);newact.sa_flags = 0;sigaction(SIGALRM,&newact,&oldact);sigemptyset(&newmask);sigaddset(&newmask,SIGALRM);sigprocmask(SIG_BLOCK,&newmask,&oldmask);alarm(seconds);suspmask = oldmask;sigdelset(&suspmask,SIGALRM);sigsuspend(&suspmask);unslept = alarm(0);sigaction(SIGALRM,&oldact,NULL);sigprocmask(SIG_SETMASK,&oldmask,NULL);return(unslept);
}int main()
{int i;for(i=0;i<5;i++){printf("hello\n");mysleep(2);}return 0;
}