现在的位置: 首页 > 综合 > 正文

精灵进程 自动守护重启进程

2013年02月05日 ⁄ 综合 ⁄ 共 1172字 ⁄ 字号 评论关闭

#include <sys/types.h>  
#include <sys/stat.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <fcntl.h>  
#include <errno.h>  
#include <unistd.h>  
#include <time.h>  
#include <syslog.h>  
#include <signal.h>

static int daemon_init(char *name, int dochdir, int doclosefd)  
{  
pid_t pid, sid, deadChildPid;  
time_t timebuf;  
int fd = -1;   

if(name == NULL)
{
return -1;
}

pid = fork();  
if  (pid  <  0)  
{  
perror( "fork ");
return -1;

//father process exit
if(pid > 0)  
{  
exit(0);  
}  

//child continues
//become session leader
if((sid = setsid()) < 0)  
{  
perror( "setsid ");
exit(1);
}  

//change working directory
if(dochdir)
{
if((chdir("/")) < 0)  
{  
perror( "chdir ");  
exit(2);  
}  
}

//clear our file mode creation mask
umask(0);

//将标准输入输出重定向到空设备
if(doclosefd)
{
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);
}
}

if((pid=fork()) == 0)  
{  
return 0; 
}
else if(pid > 0)
{
deadChildPid = wait(NULL);
printf("create a new process !\n");
if(execl(name, name, "executed by execl", NULL)<0)
           perror("Err on execl");
}

exit(0);
}  

int main(int argc, char *argv[])
{

daemon_init("./test", 0, 0);

while(1)
{  
printf("The process ID is %d\n", (int)getpid());
printf("The parent process ID is %d\n", (int)getppid());
sleep(5);  
}

return 0;
}

抱歉!评论已关闭.