守护进程:生存期长,在系统引导装入时启动,在系统关闭时终止,没有控制终端,只在后台运行 所有守护进程的父进程都是init进程
一个或多个进程构成进程组,一个或多个进程组构成会话组
守护进程编程规则: 1.创建子进程,父进程退出(使得子进程成为孤儿进程,孤儿进程运行一段时间后,由init进程统一接管) 2.调用setsid创建一个新的会话,并担任该会话组的组长 setsid作用:a>成为新会话组的首进程 b>成为一个新进程组的首进程 c>脱离控制终端 3.改变当前目录为根目录---chdir("/"); 4.重设文件权限掩码---umask(0);----对所有权限都开放 5.关闭不再需要的文件描述符-----for(i=0;i<MAXFILE;i++) { close(i); } EXAMPLE: dameon.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<fcntl.h> #include<sys/types.h> #include<unistd.h> #include<sys/wait.h> #define MAXFILE 65535 int main() { pid_t pc; int i,fd,len; char *buf="This is a Dameon\n"; len =strlen(buf); pc=fork(); if(pc<0) { printf("error fork\n"); exit(1); } else if(pc>0) exit(0); setsid(); chdir("/"); umask(0); for(i=0;i<MAXFILE;i++) close(i); while(1) { if((fd=open("/tmp/dameon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0) //open--以非缓存方式打开, {
perror("open"); exit(1); } write(fd, buf, len+1); close(fd); sleep(10); } }
守护进程出错处理: 由于守护进程完全脱离了控制终端,所以不能通过终端查看守护进程的运行情况, 通常是使用syslog服务,将出错信息输入到"/var/log/message"系统日志文件中去 Syslog是linux中的系统日志管理服务,通过守护进程syslog来维护 syslog函数: Openlog ---打开连接 Syslog ---写入消息 Closelog---关闭连接 Example: syslog_dameon.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<fcntl.h> #include<sys/types.h> #include<unistd.h> #include<sys/wait.h> #include<syslog.h> #define MAXFILE 65535 int main() { pid_t pc,sid; int i,fd,len; char *buf="This is a Dameon\n"; len =strlen(buf); pc=fork(); if(pc<0) { printf("error fork\n"); exit(1); } else if(pc>0) {
exit(0);
} openlog("demo_update",LOG_PID, LOG_DAEMON); if((sid=setsid())<0) { syslog(LOG_ERR, "%s\n", "setsid"); exit(1); } if((sid=chdir("/"))<0) { syslog(LOG_ERR, "%s\n", "chdir"); exit(1); } umask(0); for(i=0;i<MAXFILE;i++) close(i); while(1) { if((fd=open("/tmp/dameon.log",O_CREAT|O_WRONLY|O_APPEND, 0600))<0) { syslog(LOG_ERR, "open"); exit(1); } write(fd, buf, len+1); close(fd); sleep(10); } closelog(); exit(0); }