linux系统编程之进程(八):守护进程详解及创建,daemon()使用 (2)

DESCRIPTION
       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 control-
       ling tty.  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.

//调用进程必须是非当前进程组组长,调用后,产生一个新的会话期,且该会话期中只有一个进程组,且该进程组组长为调用进程,没有控制终端,新产生的group ID 和 session ID 被设置成调用进程的PID

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.

现在根据上述步骤创建一个守护进程:

以下程序是创建一个守护进程,然后利用这个守护进程每个一分钟向daemon.log文件中写入当前时间

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #define ERR_EXIT(m) \ do\ {\ perror(m);\ exit(EXIT_FAILURE);\ }\ while (0);\ void creat_daemon(void); int main(void) { time_t t; int fd; creat_daemon(); while(1){ fd = open("daemon.log",O_WRONLY|O_CREAT|O_APPEND,0644); if(fd == -1) ERR_EXIT("open error"); t = time(0); char *buf = asctime(localtime(&t)); write(fd,buf,strlen(buf)); close(fd); sleep(60); } return 0; } void creat_daemon(void) { pid_t pid; pid = fork(); if( pid == -1) ERR_EXIT("fork error"); if(pid > 0 ) exit(EXIT_SUCCESS); if(setsid() == -1) ERR_EXIT("SETSID ERROR"); chdir("/"); int i; for( i = 0; i < 3; ++i) { close(i); open("/dev/null", O_RDWR); dup(0); dup(0); } umask(0); return; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwpspp.html