除非csapp.h
标题中有些怪异,否则应该打印出四行,因为在循环的第一次迭代之后(i == 0
在增量之前),fork()
创建了两个进程,而在第二次迭代之后(i == 1
在增量之前),这两个进程中的每一个流程执行fork()
以创建另外两个流程。
当此代码在macOS 10.14.6上运行时,我得到4行内容hello
:
#include#include #include int main(void) { int i; for (i = 0; i < 2; i++) fork(); printf("hello\n"); exit(0); }
输出:
hello hello hello hello
但是,我所提供的工具远远超过了问题中显示的最少代码,就像这样:
#include#include int main(void) { int i; printf("P0: PID = %d, PPID = %d\n", (int)getpid(), (int)getppid()); fflush(stdout); for (i = 0; i < 2; i++) { int pid = fork(); printf("PF: i = %d, PID = %d, PPID = %d, fork = %d\n", i, (int)getpid(), (int)getppid(), pid); fflush(stdout); } printf("Hello: PID = %d, PPID = %d\n", (int)getpid(), (int)getppid()); return(0); }
注意fflush()
避免大量使用printf()
后fork()
的异常。
我从中得到的示例输出是:
P0: PID = 5039, PPID = 916 PF: i = 0, PID = 5039, PPID = 916, fork = 5042 PF: i = 1, PID = 5039, PPID = 916, fork = 5043 Hello: PID = 5039, PPID = 916 PF: i = 0, PID = 5042, PPID = 5039, fork = 0 PF: i = 1, PID = 5043, PPID = 1, fork = 0 Hello: PID = 5043, PPID = 1 PF: i = 1, PID = 5042, PPID = 1, fork = 5044 Hello: PID = 5042, PPID = 1 PF: i = 1, PID = 5044, PPID = 5042, fork = 0 Hello: PID = 5044, PPID = 5042
注意,报告了两个过程,PPID = 1
因为父过程(5039)已经退出。添加一个循环来等待孩子死亡并报告他们的退出状态是可行/明智的。
#include… int corpse; int status; while ((corpse = wait(&status)) > 0) { printf("WT: PID = %d, PPID = %d, child %d exited 0x%.4X\n", (int)getpid(), (int)getppid(), corpse, status); fflush(stdout); }
您在CentOS上能得到什么?
我正在终端窗口中从命令行运行程序。如果从IDE或其他方式运行此程序,则可能会丢失孤立进程的输出。添加wait()
循环将阻止第一个进程退出,直到其所有(两个)子进程都退出为止,从而有序显示4条“ Hello”行。我对输出格式进行了重新设计,以便于阅读输出。
#include#include #include int main(void) { int i; printf("P0: PID = %5d, PPID = %5d\n", (int)getpid(), (int)getppid()); fflush(stdout); for (i = 0; i < 2; i++) { int pid = fork(); printf("PF: PID = %5d, PPID = %5d, i = %d, fork = %5d\n", (int)getpid(), (int)getppid(), i, pid); fflush(stdout); } printf("hello\n"); printf("HO: PID = %5d, PPID = %5d\n", (int)getpid(), (int)getppid()); fflush(stdout); int corpse; int status; while ((corpse = wait(&status)) > 0) { printf("WT: PID = %5d, PPID = %5d, child %5d exited 0x%.4X\n", (int)getpid(), (int)getppid(), corpse, status); fflush(stdout); } printf("EX: PID = %5d, PPID = %5d\n", (int)getpid(), (int)getppid()); return(0); }
样本输出(无孤立进程):
P0: PID = 5245, PPID = 916 PF: PID = 5245, PPID = 916, i = 0, fork = 5248 PF: PID = 5248, PPID = 5245, i = 0, fork = 0 PF: PID = 5245, PPID = 916, i = 1, fork = 5249 hello HO: PID = 5245, PPID = 916 PF: PID = 5248, PPID = 5245, i = 1, fork = 5250 PF: PID = 5249, PPID = 5245, i = 1, fork = 0 hello HO: PID = 5248, PPID = 5245 hello HO: PID = 5249, PPID = 5245 EX: PID = 5249, PPID = 5245 PF: PID = 5250, PPID = 5248, i = 1, fork = 0 hello HO: PID = 5250, PPID = 5248 EX: PID = 5250, PPID = 5248 WT: PID = 5245, PPID = 916, child 5249 exited 0x0000 WT: PID = 5248, PPID = 5245, child 5250 exited 0x0000 EX: PID = 5248, PPID = 5245 WT: PID = 5245, PPID = 916, child 5248 exited 0x0000 EX: PID = 5245, PPID = 916