【发布时间】:2014-05-11 13:44:07
【问题描述】:
所以我一直在为我的操作系统类编写代码,在我的项目中,我必须在命令行上为每个文件创建一个新的子进程,并将信息从子进程传递到父进程。我们应该重新创建 Unix 的 wc 实用程序(我已经处理了这部分)。
到目前为止我尝试过的是:
for(i=0; i<argcount; i++){
int pid;
pid = fork();
if(pid == 0){
/* Child Process */
/* Close read pipes */
close(l_pipe[0]);
close(w_pipe[0]);
close(c_pipe[0]);
wc(lflag, wflag, cflag, filenames[i]);
} else {
/* Parent Process for piping */
/* Close write pipes */
close(l_pipe[1]);
close(w_pipe[1]);
close(c_pipe[1]);
/* Read from pipes */
read(l_pipe[0], &buffer, sizeof(count_t));
lines+=buffer;
read(w_pipe[0], &buffer, sizeof(count_t));
words+=buffer;
read(c_pipe[0], &buffer, sizeof(count_t));
bytes+=buffer;
}
}
但是,这会产生与孩子一样多的父母,这显然是错误的。我不确定我应该在哪里分叉。我必须在子进程和父进程之间使用管道,并且我确信父进程需要 read() 的次数与子进程 write() 的次数一样多。
感谢您提供的任何建议。
【问题讨论】: