实验:sigsuspend(),sigprocmask()

实验:sigsuspend(),sigprocmask()


源代码:
  1. /*
  2. * Program: pause_suspend.c
  3. * To test the difference between sigsuspend() and paus().
  4. * Author: zsl
  5. * Date: 2014-10-17
  6. * First release.
  7. * 参见网页:http://blog.csdn.net/liwentao1091/article/details/6619089
  8. *
  9. * */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <signal.h>
  13. #include <unistd.h>
  14. #include <string.h>
  15. /*
  16. * Handler for SIGINT (Ctrl-C), SIGQUIT (Ctrl-\)
  17. * */
  18. void sig_func(int signo)
  19. {
  20. if ( SIGINT == signo ) // just print a line.
  21. {
  22. printf(" SIGINT is processing...\n ");
  23. }
  24. if ( SIGQUIT == signo ) // print a line and exit.
  25. {
  26. printf(" SIGQUIT is processing ...\n ");
  27. printf(" Now exiting ...\n ");
  28. exit(EXIT_SUCCESS);
  29. }
  30. }
  31. int main(void)
  32. {
  33. int i;
  34. sigset_t maskset, set_quit;
  35. sigemptyset(&maskset);
  36. sigemptyset(&set_quit); // initialize two sets.
  37. sigaddset(&maskset, SIGINT); // mask SIGINT
  38. sigaddset(&set_quit, SIGQUIT); // suspend SIGQUIT
  39. // signal the two signals: SIGINT, SIGQUIT
  40. signal(SIGINT, sig_func);
  41. signal(SIGQUIT, sig_func);
  42. while(1)
  43. {
  44. /* First to mask the signal of the process: SIGINT */
  45. sigprocmask(SIG_BLOCK, &maskset, NULL);
  46. for(i = 0; i < 10; i ++)
  47. {
  48. write(1, "* ", strlen("* "));
  49. sleep(1);
  50. }
  51. printf("\n");
  52. #if 1
  53. /*
  54. * while sigsuspend(), SIGQUIT is blocked.
  55. * but SIGINT is unblocked.
  56. * If you want to execute the two signals, you
  57. * should Ctrl-\, then Ctrl-C.
  58. * */
  59. printf("Before sigsuspend() ... \n");
  60. sigsuspend(&set_quit);
  61. #else
  62. sigprocmask(SIG_UNBLOCK, &maskset, NULL);
  63. pause();
  64. #endif
  65. }
  66. return 0;
  67. }
程序的运行:
在打印“*  ”的时候,SIGINT (Ctrl-C)被 阻塞了。而SIGQUIT没有被阻塞,只要Ctrl-\就会终止程序。
在sigsuspend() 的时候,SIGQUIT (Ctrl-\)被阻塞了,而SIGINT 没有被阻塞,只要 Ctrl-C 就会进入 signal handler 中执行。。
如果想在 sigsuspend() 中对两个信号都进行处理,那么在 sigsuspend() 的时候先 SIGQUIT, 然后 SIGINT。
如下是执行效果图:
实验:sigsuspend(),sigprocmask()
上一篇:详解Android中的屏幕方向


下一篇:java web学习总结(十八) -------------------过滤器的高级使用