- 论坛徽章:
- 0
|
If we want to write a process so that it forks a
child but we don't want to wait for the child to complete and we don't want the child to become a zombie until
we terminate, the trick is to call fork twice.- #include "apue.h"
- #include <sys/wait.h>
- int
- main(void)
- {
- pid_t
- pid;
- if ((pid = fork()) < 0) {
- err_sys("fork error");
- } else if (pid == 0) {
- /* first child */
- if ((pid = fork()) < 0)
- err_sys("fork error");
- else if (pid > 0)
- exit(0);
- /* parent from second fork == first child */
- /*
- * We're the second 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(2);
- printf("second child, parent pid = %d\n", getppid());
- exit(0);
- }
- if (waitpid(pid, NULL, 0) != pid)
- err_sys("waitpid error");
- /* wait for first child */
- /*
- * We're the parent (the original process); we continue executing,
- * knowing that we're not the parent of the second child.
- */
- exit(0)
- }
复制代码 没看出来两次fork与一次fork有什么区别,换言之它所说的这个“trick",没看出有什么意义。
如果写一个程序fork出子进程,然后你进程退出,子进程交给init了,该子进程也没有成为僵尸吧,也没有在wait它,这不是已经达到了文中的要求?
而这个trick里,无非是A fork B, B fork C , B exit ,A exit,C controled by init。抛弃A进程,剩下的过程跟直接写一个程序B fork C有区别么? |
|