#include <stdlib.h>
#include <signal.h>
#include <sys/prctl.h>
#include <sys/wait.h>
void handle_signal(int signo)
{
if (signo == SIGHUP)
{
exit(0);
}
}
void run_sub_process()
{
//实现自己子进程处理逻辑
}
int main(int argc, char **argv)
{
//调用daemon函数创建守护进程
if (daemon(1,1) < 0)
{
std::cout << "set daemon fail: " << std::endl;
return -1;
}
while (1)
{
//fork函数创建子进程
pid_t nPid = fork();
if (nPid < 0)
{ //子进程创建失败
std::cout << "can't fork process: " << std::endl;
}
else if (nPid > 0)
{
//父进程,等待子进程退出,并根据子进程的退出状态决定是否退出守护进程
int exit_status = 0;
waitpid(nPid, &exit_status, 0);
if (WEXITSTATUS(exit_status) == EXIT_CODE_EXIT_DAEMON)
exit(0);
}
else
{ //表示当前是子进程,注册SIGHUP信号的处理函数,跳出循环,进入守护进程工作状态
signal(SIGHUP, handle_signal);
prctl(PR_SET_PDEATHSIG,SIGHUP);
break;
}
}
//执行子进程工作状态
run_sub_process()
return 0;
}
04-19
2635
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)