This code demonstrates how to use the double fork
method to allow the grandchild process to become adopted by init, without risk of zombie processes.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
int main()
{
pid_t p1 = fork();
if (p1 != 0)
{
printf("p1 process id is %d", getpid());
wait();
system("ps");
}
else
{
pid_t p2 = fork();
int pid = getpid();
if (p2 != 0)
{
printf("p2 process id is %d", pid);
}
else
{
printf("p3 process id is %d", pid);
}
exit(0);
}
}
The parent will fork
the new child process, and then wait
for it to finish. The child will fork
a grandchild process, and then exit(0)
.
In this case, the grandchild doesn't do anything except exit(0)
, but could be made to do whatever you'd like the daemon process to do. The grandchild may live long and will be reclaimed by the init
process, when it is complete.