Chinaunix首页 | 论坛 | 博客
  • 博客访问: 57328
  • 博文数量: 8
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 88
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-13 16:18
个人简介

不积跬步无以至千里,不积小流无以成江河。

文章分类
文章存档

2014年(8)

我的朋友

分类: 其他UNIX

2014-11-11 17:32:53


*为什么上传的图片是这个造型,有谁造怎么修改么?

APUE:10.2关于SIGHUP发送的三种情况
1.终端接口检测到一个连接断开,则将此信号送给与该终端相关的控制进程(会话首进程)。
2.会话首进程终止,此信号送给前台进程组中的每个进程。
3.父进程终止后,进程组成孤儿进程组,则向孤儿进程组发送SIGHUP信号,然后发送SIGCONT信号。



点击(此处)折叠或打开

  1. void daemonize(){
  2.     /*进程1 第一个fork 进程,进程2第二个fork 进程,进程3 守护进程。*/    
  3.     int fd = 0 ;
  4.     int i = 0 ;
  5.     size_t len = 0;
  6.     pid_t pid;
  7.     struct sigaction sa;
  8.     struct rlimit r;
  9.     char buff[] = "this is daemon test program\n";
  10.     
  11.     signal(SIGHUP, sighup);
  12.     umask(0);
  13.     
  14.     if ( 0 > (pid = fork())) {
  15.         printf("fork error\n");
  16.         exit(0);
  17.     }else if (0 != pid) {
  18.         sleep(100);
  19.         exit(0);
  20.     }
  21.     //这里可能会由于进程1的会话首进程退出接受到SIGHUP信号
  22.     setsid();
  23.     //这里可能会由于进程2的会话首进程(即进程2,因为刚刚setsid过)退出接受到SIGHUP信号
  24.     //ignore SIGHUP signal.
  25.     sa.sa_flags = 0;
  26.     sigemptyset(&sa.sa_mask);
  27.     sa.__sigaction_u.__sa_handler = SIG_IGN;
  28.     sigaction(SIGHUP, &sa, NULL);//这里其实不设置igrone进程3(即守护进程)也不收到SIGHUP信号,因为进程3是后台进程,没有连接控制终端
  29.     
  30.     if ( 0 > (pid = fork())) {
  31.         printf("fork error\n");
  32.         exit(0);
  33.     }else if (0 != pid) {
  34.         exit(0);
  35.     }
  36.     getrlimit(RLIMIT_NOFILE, &r);
  37.     
  38.     //close standard input/output(close controlling terminal) and other files.
  39.     for (i = 0 ; i < r.rlim_cur; ++i) {
  40.         close(i);
  41.     }
  42.     i = 0;
  43.     //assign input/output/errout to /dev/null
  44.     fd = open("/dev/null", O_RDWR);
  45.     fd = dup(0);
  46.     fd = dup(0);
  47.     
  48.     
  49.     len = strlen(buff);
  50.     while (i++ < 30) {
  51.         size_t t = 0;
  52.         fd = open("/Users/panghongjiang/test.txt", O_WRONLY);
  53.         t = write(fd, buff, len);
  54.         close(fd);
  55.         if (t < len) {
  56.             exit(0);
  57.         }
  58.         
  59.         sleep(1);
  60.     }
  61. }
SIGHUP信号测试:

点击(此处)折叠或打开

  1. void sighup(int signo) {
  2.     printf("pid=[%d]\n",getpid());
  3.     exit(0);
  4. }
  5. int main(){
  6.     signal(SIGHUP, sighup);
  7.     pause();
  8.     return 0;
  9. }

命令:
shell> unix_test > test1.txt &(后台进程)
shell> unix_test > test2.txt &(后台进程
shell> unix_test > test3.txt &(后台进程
shell> unix_test > test4.txt &(后台进程
shell> unix_test > test5.txt   (前台进程)

kill -9 【shell的pid】则test5.txt中写入pid=xxx示最后一个unix_test进程获取了SIGHUP信号,而其他unix_test用ps - axj命令PPID已经变成1,过继给了init或launch进程。





阅读(6111) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~