博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
精灵进程 自动守护重启进程
阅读量:3561 次
发布时间:2019-05-20

本文共 1325 字,大约阅读时间需要 4 分钟。

#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;
}

转载地址:http://vsprj.baihongyu.com/

你可能感兴趣的文章
SpringBoot入门--自动配置
查看>>
springboot读取配置文件 例:读取配置文件的优先顺序;在主配置文件中激活其他配置文件;加载非主配置文件
查看>>
自动配置原理
查看>>
TCP协议
查看>>
关于Linux系统使用遇到的问题-1:vi 打开只读(readonly)文件如何退出保存?
查看>>
redis 持久化详解,RDB和AOF是什么?他们优缺点是什么?运行流程是什么?
查看>>
spring注解版(一)
查看>>
SpringBoot中访问控制层(controller)得不到Json数据
查看>>
react项目报出警告Warning: Cannot update during an existing state transition (such as within `render`).
查看>>
BFC(Block Formatting Context)
查看>>
什么是作用域,什么是闭包,什么是作用域链
查看>>
惰性求值,面向对象
查看>>
数据结构之列表
查看>>
发布/订阅模式 vs 观察者模式
查看>>
es5中的arguments对象
查看>>
git本地仓库和远程仓库关联,分支重命名
查看>>
js对象的深拷贝,你真的觉得很简单吗?
查看>>
你真的了解map方法吗?手动实现数组map方法。
查看>>
带你手动实现call方法,让你收获满满
查看>>
前端知识体系
查看>>