[分配] 所以我用C编写了一个程序来计算行数,字数和数量。输入文件的字符(包括-l -w -c修饰符)。现在我必须创建与命令行上的文件一样多的进程,每个进程只计算一个文件并将其结果写入管道。父进程需要从管道中读取并显示总计。我还应该显示计算每个文件的进程ID。这是我的整个程序,但我的问题发生在main():
...
if (pipe(pd) < 0)
error_exit("Pipe failed");
for (i = 1; i < argc || noFile == true; i++)
{
pid = fork();
if (pid == (pid_t)0)
{
//I suppose this is the child process
...
result = WordCount(fileRead);
//close it up
close(pd[1]);
if (write(pd[1], &result, sizeof(struct CountObj)) == -1)
error_exit("Write failed");
return 0;
}
else if (pid < (pid_t)0)
{
//I suppose the fork failed
error_exit("Fork failed");
}
else
{
//I suppose this is the parent process
close(pd[0]);
isParent = true;
if (read(pd[0], &result, sizeof(struct CountObj)) == -1)
error_exit("Read failed");
... [print counts]
if (fileCount > 1)
{
total.lines += result.lines;
total.words += result.words;
total.chars += result.chars;
}
}
}
if (isParent == true && fileCount > 1)
{
... [print totals]
}
return 0;
}
这是我目前的输出:
ryan@chrx:~/Documents/OS-Projects/Project6_Pipes$ ./a.out multi_line short_line
ERROR: Read failed - bye!
ryan@chrx:~/Documents/OS-Projects/Project6_Pipes$
ERROR: Write failed - bye!
^C
我假设问题可能是在读取/写入我的CountObj结构的大小时。还有什么我可能做错了吗?
答案 0 :(得分:1)
您正在捕捉错误,因为您要从您刚刚关闭的文件中读取。
close(pd[0]);
isParent = true;
if (read(pd[0], &result, sizeof(struct CountObj)) == -1)
error_exit("Read failed");
这很简单:你在fork()之前创建一个管道,你fork():
//create a process for each file & print the count of words, lines & characters
if (pipe(pd) < 0)
error_exit("Pipe failed");
for (i = 1; i < argc || noFile == true; i++)
{
pid = fork();
如果代码在子代上运行,那么并关闭一端(让我们专门阅读) - 因为孩子只需要写。你分别在父母身上关闭(作家fd)。