守护进程

沙诺 posted @ 2012年10月02日 21:57 in Linux网络编程 , 878 阅读

今天写了一个简单的守护进程,算是网络编程入一下门吧

首先还是把创建守护进程的步骤写一下(5步):

1、fork()调用,创建子进程,父进程退出(这样是子进程成为一个orphan progress,进而由init进程托管)

2、调用setsid(),创建一个新的进程组,新的会话组,担任该会话组的组长,并脱离终端。(此处有疑问,还请高手解释

3、改变当前目录的根目录,chdir();

4、重设文件权限掩码,umask(0);

5、关闭不在需要的文件描述符,close()。

接下来是代码部分:

 

#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 Daemon\n";
len = strlen ( buf );
pc = fork();
if( pc < 0 ){
printf("error fork\n");
exit(1);
}
else if( pc > 0 ){
exit(0);
}
openlog("update_daemon",LOG_PID, LOG_DAEMON);
sid = setsid();
if(sid < 0){
syslog(LOG_ERR,"%s\n","setsid");
exit(1);
}
sid = chdir("/");
if(sid < 0){
syslog(LOG_ERR,"%s\n","chdir");
exit(1);
}
 
umask(0);
for(i=0; i<MAXFILE; i++){
close(i);
}
fd = open("/home/shanuo/yang.log",O_CREAT|O_WRONLY|O_APPEND,0600);
while(1){
if(fd < 0){
syslog(LOG_ERR,"open");
exit(1);
}
write(fd,buf,len+1);
sleep(5);
}
close(fd);
closelog();
// printf("%d\n",len);
 
  return 0;
}
这个代码是带出错处理的:采用系统日志的方式。
Avatar_small
things to do 说:
2023年4月25日 03:44

I have always loved research and it's been actually the cause of my successful finding about all the fun things to do. I used to be doing a search on the net, I discovered a wonderful post regarding the subject of the article thatt I will have to share with your followers. Don't have any ideas for holiday? There are plenty of things to do near me around your location that you can find there.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter