如果你想讓一個程序fork一個子程序,單不要它等待子程序終止,也不希望子程序處于将死狀态直到父程序終止,通過fork倆次就可以讓 init 程序接管你的程序
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int
main(void)
{
pid_t pid;
printf("current pid = %ld\n", (long)getpid());
if ((pid = fork()) < ) {
printf("fork errot ");
} else if (pid == ) { /* first child */
if ((pid = fork()) < ) /* second child */
printf("fork errot ");
else if (pid > ) {
printf("exit pid = %ld\n", (long)getpid());
exit(); /* end the parent of the first child */
}
/*
* We're the scond child;our parent becomes init as soon
* as our real parent calls exit() in the statement above.
* Here's where we'd continue executing, knowing that when
* we're done, init will reap our status.
sleep();
printf("scond child , parent pid = %ld\n", (long)getppid());
exit();
}
if (waitpid(pid, NULL, ) != pid)
printf("waitpid error\n");
exit();
}
檢視程序是否是init 程序
ps aux | grep
是我最後在shell 輸出的 parent pid ,我原來以為會是程序 呢,結果不是
我檢視了 發現它也是一個init 程序,是以如果你輸出的不是 那就自己檢視一下
是否是init 程序。