这个项目的目标是使用管道和进程之间的通讯,来执行一个已经以多进程方式编写的行数统计程序(每个参数一个进程)。我正在努力使单个进程运行成功,然后再扩展到处理多个参数。
给定两个可执行文件 lc1 和 lc2,我希望 lc2 建立一个到 lc1 的 stdout 文件描述符的管道,这样当调用 execlp("lc1", argv[1], NULL) 时,输出将会被 while ((c= read(pipefd[0], readin, SIZE)) > 0) 读取。
根据我的 Unix 书籍,我应该使用 open、dup2、close 方法将 stdout 重定向到 stdin,这是我的代码:
给定两个可执行文件 lc1 和 lc2,我希望 lc2 建立一个到 lc1 的 stdout 文件描述符的管道,这样当调用 execlp("lc1", argv[1], NULL) 时,输出将会被 while ((c= read(pipefd[0], readin, SIZE)) > 0) 读取。
根据我的 Unix 书籍,我应该使用 open、dup2、close 方法将 stdout 重定向到 stdin,这是我的代码:
int pid, c, i;
char *readin= (char *)malloc(sizeof(SIZE));
if (pipe(pipefd)== -1)
perror("Can't open a pipe\n");
for (i=1; i< argc; i++){
if ((pid= fork())==-1)
perror("Can't fork\n");
run(argv[i]);
}
//close pipe
close(1);
if (dup2(pipefd[0], 0)==-1)
perror("Can't redirect stdin");
close(pipefd[1]);
for (i=1; i< argc; i++){
if ((wait(NULL))== -1)
perror("Wait error");
while ((c= read(pipefd[0], readin, SIZE)) > 0){;
//print buf count
total += atoi(readin);
}
}
run函数是
void run(char *f){
int fp;
if ((fp= open(f, O_RDONLY)) == -1)
perror("Can't open the file");
close(pipefd[0]);
dup2(pipefd[1], 1);
close(pipefd[1]);
execlp("ls1", f, NULL);
}
当我尝试执行这段代码时,出现了一个标准输入重定向错误,显示坏的文件描述符。为什么会出现这种情况?请提供任何有用的提示来解决这个问题。
*readin= (char *)malloc(SIZE);
。 - GWW