linux下创建后台守护进程实例

来源:互联网 发布:dvi线和vga线的端口 编辑:程序博客网 时间:2024/06/11 12:48
步骤:
1. 父进程通过fork函数创建一个子进程,然后父进程退出
2. 子进程中使用setsid函数创建一个新的会话
3. 切换进程的工作目录到根目录
4. 设置进程的umask为0
5. 关闭不需要的文件操作符
 
实例代码:
 
#include <stdio.h>
#incude <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/time.h>
 
int main(int argc, char* argc)
{
   pid_t pid, sid;
  // 创建一个子进程
   pid = fork();
   if (pid < 0)
   {
       perror("fork");
       exit(EXIT_FAILURE);
   } 
   if (pid > 0)
   {
      //主进程退出
      exit(EXIT_SUCCESS);
   }
   
   // 子进程中,创建一个新的会话
   if ((sid = setsid()) < 0)
   {
      perror("setsid");
      exit(EXIT_FAILURE);
   }
   
   // 重新设置文件权限模式
   umask(0);
   
   //关闭从主进程中继承来的不需要的输入输出描述符  
   close(STDIN_FILENO);
   close(STDOUT_FILENO);
   close(STDERR_FILENO);
 
   // 实现守护进程需完成的工作
   int i = 0;
   //struct timeval
   //{
   //          long    tv_sec;          //seconds 
   //          long    tv_usec;        // microseconds 
   //};
   struct timeval;
   timeval.tv_sec = 1;
   timeval.tv_usec = 0;
   while(i < 10000)
   {
      printf("To do your work\n");
      select(0, NULL, NULL, NULL, &timeval);
   }  
   
   return 0;
}
原创粉丝点击