- #include <signal.h>
-
int sigsuspend(const sigset_t *sigmask)
将进程的信号屏蔽字设置为sigmask的值。在捕捉到一个信号或是发生了一个信号终止该进程之前,该进程被挂起。如果捕捉到一个信号并从该信号处理程序返回,则sigsuspend返回,并将进程的信号屏蔽字设置为调用sigsuspend之前的值
- #include "apue.h"
-
static void sig_int(int);
-
-
int
-
main(void)
-
{
-
sigset_t newmask,oldmask,waitmask;
-
pr_mask("program start:");
-
-
if (signal(SIGINT,sig_int) == SIG_ERR)
-
err_sys("signal(SIGINT) error");
-
sigemptyset(&waitmask);
-
sigaddset(&waitmask,SIGUSR1);
-
sigemptyset(&newmask);
-
sigaddset(&newmask,SIGINT);
-
-
/*
-
*block sigint and save current signal mask
-
*/
-
if (sigprocmask(SIG_BLOCK,&newmask,&oldmask) < 0)
-
err_sys("sig_block error");
-
-
/*
-
* critical region code
-
*/
-
printf("this is critical region code \n");
-
pr_mask("in critical region code");
-
-
/*
-
* Pause allowing all signals except sigusr1
-
*/
-
if (sigsuspend(&waitmask) != -1)
-
err_sys("sigsuspend error");
-
pr_mask("after return from suspend");
-
/*
-
*
-
* reset signal mask which unblocks sigint
-
*/
-
-
if (sigprocmask(SIG_SETMASK,&oldmask,NULL) <0)
-
err_sys("sig_setmask error");
-
/*
-
* and continue processing
-
*/
-
pr_mask("program exit");
-
exit(0);
-
}
-
static void
-
sig_int(int signo)
-
{
-
pr_mask("\n in sig_int");
-
}
- #include "apue.h"
-
#include <errno.h>
-
-
void pr_mask(const char *str)
-
{
-
sigset_t sigset;
-
int errno_save;
-
-
errno_save = errno ; /* we can be called by signal handles */
-
if (sigprocmask(0,NULL,&sigset) < 0)
-
err_sys("sigprocmask error");
-
printf("%s",str);
-
-
if (sigismember(&sigset,SIGINT)) printf("SIGINT");
-
if (sigismember(&sigset,SIGQUIT)) printf("SIGQUIT");
-
if (sigismember(&sigset,SIGUSR1)) printf("SIGUSR1");
-
if (sigismember(&sigset,SIGALRM)) printf("SIGALRM");
-
/* remaining signals can go here */
-
printf("\n");
-
errno = errno_save;
-
}
- #include "apue.h"
-
/* reliable version of signal() ,using posix signaction()*/
-
Sigfunc *
-
signal(int signo,Sigfunc * func)
-
{
-
struct sigaction act,oact;
-
-
act.sa_handler = func;
-
sigemptyset(&act.sa_mask);
-
act.sa_flags = 0;
-
if ( signo == SIGALRM){
-
#ifdef SA_INTERRUPT
-
act.sa_flags |= SA_INTERRUPT;
-
#endif
-
} else{
-
#ifdef SA_RESTART
-
act.sa_flags |= SA_RESTART;
-
#endif
-
}
-
if (sigaction(signo,&act,&oact) < 0)
-
return(SIG_ERR);
-
return(oact.sa_handler);
-
}
program flow:
main()
block sig_int
critical code
sigprocmask ------------ set sig_int 屏蔽字
pr_mask() ----------- sig_int
sigsuspend() ------------set sig_usr1 并使进程挂起
ctr+c
中断处理程序
pr_mask()-------------sig_int,sigusr1
返回
exit()
- ubuntu@ubuntu-virtual-machine:~/Desktop/apue$ gcc -Wall -o c10-15 c10-15.c error
-
.c pr_mask.c c10-12.c
-
-
ubuntu@ubuntu-virtual-machine:~/Desktop/apue$ ./c10-15
-
-
program start:
-
-
this is critical region code
-
-
in critical region code
- SIGINT
-
-
^C
-
-
in sig_intSIGINTSIGUSR1
-
-
after return from suspend
- SIGINT
-
-
program exit
阅读(986) | 评论(0) | 转发(0) |