daemon 实例程序

来源:互联网 发布:马云菜鸟网络 编辑:程序博客网 时间:2024/06/14 13:13

/*
 * daemon.c
 *
 *  Created on: 2011-11-9
 *      Author: lc
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#define MAXFD 65535

int main(int argc, char **argv) {

 pid_t cid;

 int i;
 int fd;
 int len;
 char buf[] = "this is daemon running...\n";

 len = strlen(buf);

 //step 1 : 创建子进程,关闭父进程
 cid = fork();
 if (cid < 0) {
  perror("fork");
  exit(1);
 } else if (cid > 0) {
  exit(0);
 } else {

  //子进程执行
  //step 2 : 在子进程中创建新的session和进程组,使该进程成为新进程组和新session的leader进程 ,
  //使子进程脱离于原父进程相同的 控制终端(CTTY),进程组号,session

  setsid();
  //step 3 : 改变子进程工作目录,使之与父进程不同
  chdir("/");
  //step 4 : 改变umask掩码
  umask(0);
  //step 5 : 关闭继承的打开的文件
  for (i = 0; i < MAXFD; i++) {
   close(i);
  }

  //守护进程执行
  while (1) {
   if ((fd = open("/tmp/daemon.log", O_CREAT | O_APPEND | O_WRONLY,
     0777)) < 0) {
    perror("open");
    exit(1);
   }

   write(fd, buf, len + 1);

   close(fd);
   sleep(10);
  }

 }

 return 0;
}

原创粉丝点击