Linux进程实践(5) --守护进程

来源:互联网 发布:applem2引擎完整源码 编辑:程序博客网 时间:2024/05/17 00:05

概述

   守护进程是在需要在后台长期运行不受终端控制的进程,通常情况下守护进程在系统启动时自动运行,在服务器关闭的时候自动关闭;守护进程的名称通常以d结尾,比如sshd、xinetd、crond、atd等。


守护进程编程规则 

   调用umask将文件模式创建屏蔽字设置为一个已知值(通常是0)

   调用fork(),创建新进程,它会是将来的守护进程

   然后使父进程exit,保证子进程不是进程组组长

   调用setsid创建新的会话

      会话:是一个或者多个进程组的集合,通常一个会话开始与用户登录,终止于用户退出。在此期间,该用户运行的所有进程都属于这个会话期。

   将进程的当前目录改为根目录 (如果把当前目录作为守护进程的目录,当前目录不能被卸载,它作为守护进程的工作目录了。)

   关闭不再需要的文件描述符

   将标准输入、标准输出、标准错误重定向到/dev/null

setsid

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. pid_t setsid(void);  

 setsid() creates a new session if the calling process is not a process group leader.  The calling process is the leader of the new session, the process group  leader  of  the  new process  group,  and has no controlling terminal.  The process group ID and session ID of the calling process are set to the PID of the calling process.  The calling process  will be the only process in this new process group and in this new session.

/*当调用进程不是一个进程组的组长时,Setsid创建一个新的会话;调用者进程会是这个会话期唯一的一个进程,且是该进程组的组长;调用者进程id是组id,也是会话期的id。不能用进程组组长去调用setsid函数*/

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //示例:  
  2. int main()  
  3. {  
  4.     pid_t pid = fork();  
  5.     if (pid == -1)  
  6.         err_exit("fork error");  
  7.     else if (pid != 0)  
  8.         exit(EXIT_SUCCESS);  
  9.   
  10. //    //查看下面这一部分代码在注释的前后有什么变化  
  11. //    pid_t id = setsid();  
  12. //    if (id == -1)  
  13. //        err_exit("setsid error");  
  14. //    else  
  15. //        cout << "new session id = " << id << endl;  
  16.   
  17.     cout << "getpid = " << getpid() << endl;  
  18.     cout << "getpgid = " << getpgid(getpid()) << endl;  
  19.   
  20.     return 0;  
  21. }  

RETURN VALUE

       On  success,  the  (new)  session  ID  of  the  calling  process  is returned.  On error, (pid_t) -1 is returned, and errno is set to indicate the error.

Linux中的守护进程API

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. int daemon(int nochdir, int noclose);  

参数:

   nochdir:=0将当前目录更改至“/”

   noclose:=0将标准输入、标准输出、标准错误重定向至“/dev/null”

DESCRIPTION

       The  daemon()  function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons. If nochdir is zero, daemon() changes the calling process's current working  directory  to the root directory ("/"); otherwise, the current working directory is left unchanged. If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //示例:自己动手写daemon函数(一个比较简单的示例)  
  2. bool myDaemon(bool nochdir, bool noclose)  
  3. {  
  4.     umask(0);  
  5.   
  6.     pid_t pid = fork();  
  7.     if (pid == -1)  
  8.         err_exit("fork error");  
  9.     else if (pid != 0)   //parent  
  10.         exit(0);  
  11.   
  12.     setsid();  
  13.   
  14.     if (nochdir == 0)  
  15.         chdir("/");  
  16.     if (noclose == 0)  
  17.     {  
  18.         int i;  
  19.         for (i=0; i < 3; ++i)  
  20.             close(i);  
  21.         open("/dev/null", O_RDWR);  //相当于把0号文件描述符指向/dev/null  
  22.         dup(0); //把0号文件描述符 赋值给空闲的文件描述符 1  
  23.         dup(0); //把0号文件描述符 赋值给空闲的文件描述符 2  
  24.     }  
  25.   
  26.     return true;  
  27. }  
  28.   
  29. //测试  
  30. int main(int argc, char *argv[])  
  31. {  
  32.     myDaemon(0, 0); //0表示做出改变(当前目录,文件描述符),1表示不改变  
  33.     printf("test ...\n");  
  34.     while (true)  
  35.     {  
  36.         sleep(1);  
  37.     }  
  38.     return 0;  
  39. }  

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //一个比较经典和完善的实例;来自《APUE》  
  2. #include "apue.h"  
  3. #include <syslog.h>  
  4. #include <fcntl.h>  
  5. #include <sys/resource.h>  
  6.   
  7. bool myDaemon(const char *cmd);  
  8.   
  9. int main(int argc, char *argv[])  
  10. {  
  11.     myDaemon("xiaofang");  
  12.     while (true)  
  13.     {  
  14.         sleep(1);  
  15.     }  
  16.   
  17.     return 0;  
  18. }  
  19.   
  20. bool myDaemon(const char *cmd)  
  21. {  
  22.     umask(0);  
  23.   
  24.     //Get maximum number of file descriptors.  
  25.     rlimit rlt;  
  26.     if (getrlimit(RLIMIT_NOFILE,&rlt) < 0)  
  27.     {  
  28.         err_quit("%s: can't get file limit",cmd);  
  29.     }  
  30.   
  31.     //Become a session leader to lose controlling TTY.  
  32.     pid_t pid = fork();  
  33.     if (pid == -1)  
  34.     {  
  35.         err_quit("%s: can't fork",cmd);  
  36.     }  
  37.     if (pid != 0)   //parent  
  38.     {  
  39.         exit(0);  
  40.     }  
  41.     setsid();  
  42.   
  43.   
  44.     //Ensure future opens won't allocate controlling TTYs.  
  45.     struct sigaction sa;  
  46.     sa.sa_handler = SIG_IGN;  
  47.     sigemptyset(&sa.sa_mask);  
  48.     sa.sa_flags = 0;  
  49.     if (sigaction(SIGHUP,&sa,NULL) < 0)  
  50.     {  
  51.         err_quit("%s can't ignore SIGHUP",cmd);  
  52.     }  
  53.     if ((pid = fork()) < 0)  
  54.     {  
  55.         err_quit("%s: can't fork",cmd);  
  56.     }  
  57.     else if (pid != 0)  //Second Parent  
  58.     {  
  59.         exit(EXIT_SUCCESS);  
  60.     }  
  61.   
  62.     //change the current working directory to the root  
  63.     if (chdir("/") < 0)  
  64.     {  
  65.         err_quit("%s: can't change directory to /",cmd);  
  66.     }  
  67.   
  68.     //close all open file description  
  69.     if (rlt.rlim_max == RLIM_INFINITY)  
  70.     {  
  71.         rlt.rlim_max = 1024;  
  72.     }  
  73.     for (unsigned int i = 0; i < rlt.rlim_max; ++i)  
  74.     {  
  75.         close(i);  
  76.     }  
  77.   
  78.     //Attach file descriptors 0, 1, and 2 to /dev/null.  
  79.     int fd0 = open("/dev/null",O_RDWR);  
  80.     int fd1 = dup(0);  
  81.     int fd2 = dup(0);  
  82.   
  83.     //Initialize the log file.  
  84.     openlog(cmd,LOG_CONS,LOG_DAEMON);  
  85.     if (fd0 != 0 || fd1 != 0 || fd2 != 0)  
  86.     {  
  87.         syslog(LOG_ERR,"unexpected file descriptors %d %d %d",  
  88.         fd0,fd1,fd2);  
  89.         exit(EXIT_FAILURE);  
  90.     }  
  91.   
  92.     return true;  
  93. }  
0 0
原创粉丝点击