程序以下:服務器
守護進程.csession
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<syslog.h>ide
//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");
}
}ip
執行get
./調用守護進行it
查看守護進程記錄的內容io
若是應用在服務器上,能夠使用守護進程來監聽端口,而主程序繼續處理其它事物,在守護進程監聽到端口又connect時候,能夠記錄下client的信息,最後主程序退出時候kill 守護進程便可,這樣子也至關於fork()去處理一個鏈接事件,但能夠後臺處理,更加方便,實現真正的超級服務器設計