运行结果为:
-----------------------------
This is the NO.1 child process
Fork end.
This is the NO.1 child process
Fork end.
This is the NO.2 child process
Fork end.
This is the parent process
Fork end.
---------------------
以上运行结果可以看出,似乎子进程1运行了2次,其实不然。首先,在运行pid2=fork()前,已有主进程和子进程1存在。在主进程中pid1不为0,所以,当主进程再次生成子进程2后,能够顺利显示“This is the parent process.Fork end.”和“This is the NO.2 child process.Fork end.”;然而,在子进程1中,由于pid为1,所以即使它也生成了子进程2,但2个进程都只会运行到19行。原本应该运行进入行的子进程2却应为pid1==0在pid2==0之前,而无法进入,最终导致两次显示NO.1 child process。
代码可修改如下: