调用并产生守护进程来后台工作

来源:互联网 发布:windows api 创建窗口 编辑:程序博客网 时间:2024/05/17 06:14

程序如下:

守护进程.c

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<syslog.h>

//deamon function turn thr process who get it into a deamon progress
void deamon()
{
 pid_t pid;
 int fd;
 pid=fork();
 if(pid<0)
 {
  perror("fork error!");
  return -1;
 }
 //first step:
 if(pid!=0)
 {
  exit(0);  //father progress exit,the child be a orphan progress
 }
 //second step: call setsid() to make a new session (对话)
 pid=setsid();
 if(pid==-1)
 {
  perror("setdid error!");
  _exit(1);
 }
 // step third: change the work dir to "/"
 chdir("/");
 // step forth: close all the file disription,and  STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO to /dev/null ;重新定向标准输出,标准输入,标准错误到/dev/null
 fd=open("/dev/null",O_RDWR,0);
 if(fd!=-1)
 {
  dup2(fd,STDIN_FILENO);
  dup2(fd,STDOUT_FILENO);
  dup2(fd,STDERR_FILENO);
  if(fd>2)
  {
   close(fd);
  }
 }
 else
 {
  perror("reDingXiang error!");
  _exit(1);
 }
 //step fifth:set umask
 umask(0027);
 openlog("守护进程",LOG_CONS|LOG_PID,LOG_USER);
 int count=0;
 while(count<5)
 {
  syslog(LOG_INFO,"log info test。。。",count);
  count++;
 }
}
int main()
{
 deamon();
 sleep(1000);
 return 0;
}

 


调用守护进程.c


#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>

main()
{
 pid_t pid;
 int status;
 pid=vfork();
 if(pid<0)
 {
  perror("fork error!/n");
 }
 else if(pid==0)
 {
  execlp("./守护进程","守护进程",NULL);
 }
 else
 {
  wait(&status);
  while(1)
    printf("father wait.../n");
 }
}

 

执行

./调用守护进行

查看守护进程记录的内容

如果应用在服务器上,可以使用守护进程来监听端口,而主程序继续处理其它事物,在守护进程监听到端口又connect时候,可以记录下client的信息,最后主程序退出时候kill  守护进程即可,这样子也相当于fork()去处理一个连接事件,但可以后台处理,更加方便,实现真正的超级服务器设计