【发布时间】:2011-05-05 17:13:03
【问题描述】:
该项目的目标是使用管道和分叉来执行已经以多进程方式编写的行计数实用程序(每个参数一个进程)。我目前正在努力让单个进程在扩展以处理多个参数之前工作。
给定两个可执行文件lc1和lc2,我希望lc2建立到lc1的stdout文件描述符的管道,这样当execlp("lc1", argv[1], NULL)被调用时,输出将被读入while ((c= read(pipefd[0], readin, SIZE)) > 0)
根据我的 Unix 书,我应该使用 open、dup2、close 方法将标准输出重定向到标准输入,这是我的代码:
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);
}
}
运行函数是
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);
}
当我尝试执行此代码时,我收到一个 stdin 重定向错误,说明文件描述符错误。为什么会发生这种情况,并希望得到任何修复提示。
【问题讨论】:
-
你的 malloc 语句是错误的我认为你想要 char
*readin= (char *)malloc(SIZE); -
永远不要在 C 中转换 malloc() 的返回值。请参阅 stackoverflow.com/questions/953112/…。
-
不是你的直接问题,但你真的是说 malloc(sizeof(SIZE)) 吗?我假设 SIZE 是一个常数,所以你分配了 4 或 8 个字节左右。您可以发布更完整的代码吗?正如发布的那样,这有点难以理解。
-
SIZE其实是一个整数4096,所以我用它来分配4MB内存
-
malloc(sizeof(SIZE)) 将在您的机器上分配整数的大小。 malloc(SIZE) 其中 SIZE 的值为 4096 将分配 4k。