实验:sigsuspend(),sigprocmask()
源代码:
/*
* Program: pause_suspend.c
* To test the difference between sigsuspend() and paus().
* Author: zsl
* Date: 2014-10-17
* First release.
* 参见网页:http://blog.csdn.net/liwentao1091/article/details/6619089
*
* */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
/*
* Handler for SIGINT (Ctrl-C), SIGQUIT (Ctrl-\)
* */
void sig_func(int signo)
{
if ( SIGINT == signo ) // just print a line.
{
printf(" SIGINT is processing...\n ");
}
if ( SIGQUIT == signo ) // print a line and exit.
{
printf(" SIGQUIT is processing ...\n ");
printf(" Now exiting ...\n ");
exit(EXIT_SUCCESS);
}
}
int main(void)
{
int i;
sigset_t maskset, set_quit;
sigemptyset(&maskset);
sigemptyset(&set_quit); // initialize two sets.
sigaddset(&maskset, SIGINT); // mask SIGINT
sigaddset(&set_quit, SIGQUIT); // suspend SIGQUIT
// signal the two signals: SIGINT, SIGQUIT
signal(SIGINT, sig_func);
signal(SIGQUIT, sig_func);
while(1)
{
/* First to mask the signal of the process: SIGINT */
sigprocmask(SIG_BLOCK, &maskset, NULL);
for(i = 0; i < 10; i ++)
{
write(1, "* ", strlen("* "));
sleep(1);
}
printf("\n");
#if 1
/*
* while sigsuspend(), SIGQUIT is blocked.
* but SIGINT is unblocked.
* If you want to execute the two signals, you
* should Ctrl-\, then Ctrl-C.
* */
printf("Before sigsuspend() ... \n");
sigsuspend(&set_quit);
#else
sigprocmask(SIG_UNBLOCK, &maskset, NULL);
pause();
#endif
}
return 0;
}
程序的运行:
在打印“* ”的时候,SIGINT (Ctrl-C)被 阻塞了。而SIGQUIT没有被阻塞,只要Ctrl-\就会终止程序。
在sigsuspend() 的时候,SIGQUIT (Ctrl-\)被阻塞了,而SIGINT 没有被阻塞,只要 Ctrl-C 就会进入 signal handler 中执行。。
如果想在 sigsuspend() 中对两个信号都进行处理,那么在 sigsuspend() 的时候先 SIGQUIT, 然后 SIGINT。
如下是执行效果图: