话不多说直接上代码。
-------------father.cpp----------------
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;
static int SonNumCount = 0;
void ForkANewLife()
{
pid_t pid = fork();
if(pid == 0)
{
execvp("./child", NULL);
exit(-1);
}
else
{
printf("I have a son[%d]\n", pid);
}
SonNumCount ++;
}
void OnSignalSIGCHLD(int signo)
{
pid_t pid;
int status = 0;
pid = waitpid(-1, &status, 0);
printf("my son is dead[%d] status [%d], I will bring him a new life\n", pid, status);
if(SonNumCount >= 3)
{
printf("oh, fuck, my son [%d] has died three times,I [%d] want to go with him\n", pid, getpid());
exit(-1);
}
else
ForkANewLife();
}
int main(int argc, char *argv[])
{
printf("start father [pid:%d] process\n", getpid());
sleep(2);
printf("start to get son\n");
ForkANewLife();
signal(SIGCHLD, OnSignalSIGCHLD);
while(1)
{
printf("father alive!!!!!!!!!!\n");
sleep(5);
}
return 0;
}
------child.cpp-----------
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("start child process\n");
int count = 0;
while(count ++ != 5)
{
printf("child alive!!!!!!!!!\n");
sleep(2);
}
printf("father! I will dead!!!!\n");
return 0;
}
代码比较简单,形象的描述了守护进程的作用。父进程在3次拯救子进程未果的情况下,跟随子进程一起归西。
代码中有用到进程创建,信号捕捉,僵尸进程回收,LINUX执行目标目录文件等知识。