LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1014|回复: 4

[提问]关于daemon进程

[复制链接]
发表于 2007-8-7 13:41:32 | 显示全部楼层 |阅读模式
  1. #include <stdio.h>
  2. #include <signal.h>
  3. #include <syslog.h>
  4. #include <fcntl.h>
  5. #include <sys/resource.h>
  6. #include <stdlib.h>



  7. void deamonize(const char *cmd)
  8. {
  9.         int  i = 0;
  10.         int fd0 = 0;
  11.         int fd1 = 0;
  12.         int fd2 = 0;

  13.         pid_t pid;

  14.         struct sigaction sa;
  15.         struct rlimit rl;

  16.         umask(0);

  17.         getrlimit(RLIMIT_NOFILE, &rl);

  18.         pid = fork();
  19.         if (pid < 0)
  20.         {               
  21.                 exit(0);
  22.         }
  23.         else if (pid != 0)
  24.         {               
  25.                 exit(0);
  26.         }

  27.         setsid();

  28.         sa.sa_handler = SIG_IGN;
  29.         sigemptyset(&sa.sa_mask);
  30.         sa.sa_flags = 0;

  31.         sigaction(SIGHUP, &sa, NULL);

  32.         pid = fork();

  33.         if (pid < 0)
  34.         {               
  35.                 exit(0);
  36.         }
  37.         else if (pid != 0)
  38.         {               
  39.                 exit(0);
  40.         }
  41.        
  42.         chdir("/");

  43.         if (rl.rlim_max = RLIM_INFINITY)
  44.         {
  45.                 rl.rlim_max = 1024;
  46.         }

  47.         for (i = 0; i < 1024; i++)
  48.         {
  49.                 close (i);
  50.         }

  51.         fd0 = open ("/dev/null", O_RDWR);
  52.         fd1 = dup (0);
  53.         fd2 = dup (0);

  54.         openlog(cmd, LOG_CONS, LOG_DAEMON);
  55.        
  56.         if (fd0 != 0 || fd1 != 1 || fd2 != 2)
  57.         {
  58.                 syslog(LOG_ERR, "%d, %d, %d", fd0, fd1, fd2);
  59.                 exit (1);
  60.         }
  61. }

  62. int main ()
  63. {
  64.         deamonize("=.=");
  65. }
复制代码



APUE2里面的例子

为什么我用 ps axj 看不到我这个精灵进程呢??

问题出在什么地方了?
发表于 2007-8-7 15:04:23 | 显示全部楼层
因为你的程序已执行完毕退出了
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-8-7 15:19:38 | 显示全部楼层
额``

那我怎么保证它不退出,而是一个精灵进程呢~

用while(1)

吗??

可是,APUE上没有这么用都可以用ps axj 看到进程的,为什么呢?
回复 支持 反对

使用道具 举报

发表于 2007-8-7 15:35:57 | 显示全部楼层
如果你的进程没事做,那何必管他精灵不精灵呢
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-8-7 15:47:05 | 显示全部楼层
Post by x11
如果你的进程没事做,那何必管他精灵不精灵呢



也是哈~

如过有事情做就添加功能到里面

如果一直有事做,就把功能添加到

while(1)

循环里面

这样理解对不?
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表