【发布时间】:2013-05-05 18:03:24
【问题描述】:
在下面的代码中,我只是尝试通过标准输入将文件发送到将执行 cat OS 命令的子进程。代码编译得很好。这是我从命令行调用它的方式:
$ ./uniquify < words.txt
但是,当我运行它时,我得到一个段错误错误。如果信息应该通过管道传递给孩子,我真的很难理解流程是如何流动的。我正在尝试使代码尽可能简单,以便我可以理解它,但它还没有意义。任何帮助将不胜感激。
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#define NUM_CHILDREN 2
int main(int argc, char *argv[])
{
pid_t catPid;
int writeFds[NUM_CHILDREN];
int catFds[2];
int c = 0;
FILE *writeToChildren[NUM_CHILDREN];
//create a pipe
(void) pipe(catFds);
if ((catPid = fork()) < 0) {
perror("cat fork failed");
exit(1);
}
//this is the child case
if (catPid == 0) {
//close the write end of the pipe
close(catFds[1]);
//close stdin?
close(0);
//duplicate the read side of the pipe
dup(catFds[0]);
//exec cat
execl("/bin/cat", "cat", (char *) 0);
perror("***** exec of cat failed");
exit(20);
}
else { //this is the parent case
//close the read end of the pipe
close(catFds[0]);
int p[2];
//create a pipe
pipe(p);
writeToChildren[c] = fdopen(p[1], "w");
} //only the the parent continues from here
//close file descriptor so the cat child can exit
close(catFds[1]);
char words[NUM_CHILDREN][50];
//read through the input file two words at a time
while (fscanf(stdin, "%s %s", words[0], words[1]) != EOF) {
//loop twice passing one of the words to each rev child
for (c = 0; c < NUM_CHILDREN; c++) {
fprintf(writeToChildren[c], "%s\n", words[c]);
}
}
//close all FILEs and fds by sending and EOF
for (c = 0; c < NUM_CHILDREN; c++) {
fclose(writeToChildren[c]);
close(writeFds[c]);
}
int status = 0;
//wait on all children
for (c = 0; c < (NUM_CHILDREN + 1); c++) {
wait(&status);
}
return 0;
}
【问题讨论】:
-
你从不初始化
writeToChildren,所以你在一个错误的FILE *上调用fprintf。 -
所以添加这样的东西? writeToChildren[c] = fdopen(p[1], "w");
-
我编辑了代码并将以下内容添加到父代码中:int p[2]; //创建一个管道 pipe(p); writeToChildren[c] = fdopen(p[1], "w");
-
我仍然收到 seg fault core dump 错误...
-
您写入管道的代码假定将有两个子进程;代码创建进程只创建一个子进程。这会导致你的一些问题。您看不到有必要的近距离通话(例如,在
dup(catFds[0])之后,您需要close(catFds[0]))。您不包括对系统调用的错误检查。