- 論壇徽章:
- 0
|
原帖由 無聲無息 于 2008-10-24 16:41 發(fā)表 ![]()
平時需要在后臺執(zhí)行任務(wù)的時候,常使用nohup或者screen之類的東東,確實好用。
不過今天有一個情況有點不解,一直都這么認(rèn)為
1、nohup command 登錄后執(zhí)行command,logout后,此command不受影響的繼續(xù)運行
2 ...
調(diào)用兩次fork()就會出現(xiàn)你說的情況
APUE上的一段
- 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. The program in Figure 8.8 does this.
- We call sleep in the second child to ensure that the first child terminates before printing the parent process ID. After a fork, either the parent or the child can continue executing; we never know which will resume execution first. If we didn't put the second child to sleep, and if it resumed execution after the fork before its parent, the parent process ID that it printed would be that of its parent, not process ID 1.
- Executing the program in Figure 8.8 gives us
- $ ./a.out
- $ second child, parent pid = 1
- Note that the shell prints its prompt when the original process terminates, which is before the second child prints its parent process ID.
- Figure 8.8. Avoid zombie processes by calling 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) /* wait for first child */
- err_sys("waitpid error");
- /*
- * We're the parent (the original process); we continue executing,
- * knowing that we're not the parent of the second child.
- */
- exit(0);
- }
復(fù)制代碼 |
|