- 论坛徽章:
- 0
|
2可用积分
下面是APUE2中程序10_16,问题见程序中描述:
- #include <stdio.h>
- #include <stdlib.h>
- #include <signal.h>
- volatile sig_atomic_t quitflag;
- static void sig_handler(int signo);
- int main(int argc, char** argv)
- {
- struct sigaction act1, act2;
- sigset_t newmask, oldmask, zeromask;
- act1.sa_flags = 0;
- act1.sa_handler = sig_handler;
- sigemptyset(&act1.sa_mask);
- if(sigaction(SIGINT, &act1, NULL) < 0){
- perror("sigaction SIGINT");
- exit(1);
- }
- act2.sa_flags = 0;
- act2.sa_handler = sig_handler;
- sigemptyset(&act2.sa_mask);
- if(sigaction(SIGQUIT, &act2, NULL) < 0){
- perror("sigaction SIGQUIT");
- exit(2);
- }
- sigemptyset(&newmask);
- sigemptyset(&zeromask);
- sigaddset(&newmask, SIGQUIT);
- if(sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0){
- perror("sigprocmask SIG_BLOCK");
- exit(3);
- }
- sleep(10);//加了sleep以后,1。运行程序按ctrl+\(没有反应,因为sleep,SIGQUIT还没有被sigsuspend检测到),紧接着按ctrl+c,程序立即结束,前后操作时间没有超过10s,为什么进程会终//止呢? 2。运行程序后按ctrl+c,打印caught SIGINT(是期望结果),立即按ctrl+\,程序理解结束?但此时SIGQUIT信号应该被阻塞10s后被sigsuspend检测到并执行信号处理程序,然后//sigsuspend恢复调用前的信号屏蔽字并返回才对(在sig_handler结束后)。
- //上面的2个问题不是很明白,是我理解sigsuspend函数错了吗?谢谢大侠指点!
- while(quitflag == 0){
- sigsuspend(&zeromask);
- }
- quitflag = 0;
- if(sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0){
- perror("sigprocmask SIG_SETMASK");
- exit(4);
- }
- exit(0);
- }
- static void sig_handler(int signo)
- {
- if(signo == SIGINT){
- printf("\ncaught SIGINT\n");
- }
- if(signo == SIGQUIT){
- quitflag = 1;
- }
- }
复制代码 |
最佳答案
查看完整内容
每次给的分可真少。 我给你解释一下第一个。运行程序按ctrl+\(没有反应是因为此信号被阻塞,没有提交)。紧接着按ctrl+c,sleep会被打断,去执行sig_handler函数。sig_handler返回后,sigsuspend也会返回,并把信号屏蔽字设置为以前的屏蔽字,也就是ctrl+\信号被解除了。ctrl+\解除后,要提交这个信号,所以执行sig_handler函数,quitflag被置1,退出while循环,然后程序退出。第二个你自己分析吧。
|