将原书代码3.9略有修改
修改之一,就是将等待的内容wait或者是原书自己的r_wait,放入到父进程的代码区
原书中应该是个错误,没有把等待放入到父进程代码区,搞得子进程也在执行wait
修改之二,将子进程产生一个睡眠时间,这样可以看到输出,睡眠一个固定时间sleep(5);或者睡眠一个递增时间、用来产生仅仅一个进程sleep(5*i);或者睡眠一个随机值
#include <stdio.h>
#include <stdlib.h>#include <unistd.h>
#include <sys/wait.h>
#include "restart.h"
int main(int argc, char *argv[]) {
pid_t childpid;
int i, n;
if (argc != 2) {
fprintf(stderr, "Usage: %s n\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
for (i = 1; i < n; i++)
if ((childpid = fork()) <= 0)
break;
// 上面几行是产生N-1个子进程,其中fork返回0是子进程,fork函数有点像细胞分裂,每次总是一分为2,产生多个也是多次分裂产生,不是一次产生多个
// while(r_wait(NULL) > 0) ; /* wait for all of your children */
// while(wait(NULL) > 0) ; /* wait for all of your children */
if(childpid != 0)
{
wait(NULL);
}
if (childpid ==0)
{
sleep(20*i);
}
fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}
----------------------------------------------------------------------------------------
执行的终端的效果是等待20秒,第一个子进程信息打印出来,然后主进程信息打印出来。
然后这个父进程的显示就结束了。系统回到了linux提示符。
再过了20秒,第二个子进程的信息被显示,要注意的是这个时候第二个子进程的父进程id为1,即init,这说明第二个子进程已经变成了孤儿进程。后面也是一样,第三个、第四个。
另开一个终端,看看进程信息
// AAAusp/chapter03 % ps -ef|grep fan
96:whoareu 454 29725 0 16:20 pts/1 00:00:00 ./fanwait4 5
98:whoareu 457 454 0 16:20 pts/1 00:00:00 ./fanwait4 5
99:whoareu 459 454 0 16:20 pts/1 00:00:00 ./fanwait4 5
101:whoareu 462 454 0 16:20 pts/1 00:00:00 ./fanwait4 5
102:whoareu 464 454 0 16:20 pts/1 00:00:00 ./fanwait4 5
106:whoareu 472 30325 0 16:20 pts/2 00:00:00 grep -n fan
// AAAusp/chapter03 % ps -ef | grep fan
97:whoareu 459 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
99:whoareu 462 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
100:whoareu 464 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
108:whoareu 561 30325 0 16:20 pts/2 00:00:00 grep -n fan
// AAAusp/chapter03 % ps -ef | grep fan
97:whoareu 459 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
99:whoareu 462 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
100:whoareu 464 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
108:whoareu 572 30325 0 16:20 pts/2 00:00:00 grep -n fan
// AAAusp/chapter03 % ps -ef | grep fan
99:whoareu 462 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
100:whoareu 464 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
108:whoareu 582 30325 0 16:20 pts/2 00:00:00 grep -n fan
// AAAusp/chapter03 % ps -ef | grep fan
100:whoareu 464 1 0 16:20 pts/1 00:00:00 ./fanwait4 5
108:whoareu 592 30325 0 16:20 pts/2 00:00:00 grep -n fan
// AAAusp/chapter03 % ps -ef | grep fan
108:whoareu 592 30325 0 16:20 pts/2 00:00:00 grep -n fan