【发布时间】:2012-05-26 14:54:50
【问题描述】:
我在 Linux 中有一个任务,但我无法让它工作。
我有一个接收文本文件作为参数的程序。然后它使用fork() 创建一个子进程,并将作为参数接收的文本文件的内容逐行发送到子进程。子进程需要统计行数,并将收到的行数返回给父进程。
这是我到目前为止所拥有的,但有些子进程没有收到所有行。对于我的测试,我使用了一个包含 9 行的文本文件。父进程发送了 9 行字符串,但子进程只收到了 2 或 3 行。
我做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string[80];
char readbuffer[80];
int pid, p[2];
FILE *fp;
int i=0;
if(argc != 2)
{
printf("Syntax: %s [file_name]\n", argv[0]);
return 0;
}
fp = fopen(argv[1], "r");
if(!fp)
{
printf("Error: File '%s' does not exist.\n", argv[1]);
return 0;
}
if(pipe(p) == -1)
{
printf("Error: Creating pipe failed.\n");
exit(0);
}
// creates the child process
if((pid=fork()) == -1)
{
printf("Error: Child process could not be created.\n");
exit(0);
}
/* Main process */
if (pid)
{
// close the read
close(p[0]);
while(fgets(string,sizeof(string),fp) != NULL)
{
write(p[1], string, (strlen(string)+1));
printf("%s\n",string);
}
// close the write
close(p[1]);
wait(0);
}
// child process
else
{
// close the write
close(p[1]);
while(read(p[0],readbuffer, sizeof(readbuffer)) != 0)
{
printf("Received string: %s\n", readbuffer);
}
// close the read
close(p[0]);
}
fclose(fp);
}
【问题讨论】:
-
这是作业吗?如果是这样,请添加适当的标签。无论如何,这里有一个提示:如果数据流中有
'\0',read不会停止读取。 -
子进程收到“2 或 3 行”还是其
read()返回“2 或 3 次”?这些是不同的场景。我敢打赌是后者。