【发布时间】:2017-10-11 19:59:20
【问题描述】:
我正在尝试学习如何使用 pipe() 和 fork() 系统调用。我正在使用管道和叉子创建父进程和子进程,其中子进程将从文本文件中读取一个字符,然后通过管道将其发送到父进程,然后父进程会将字符输出到控制台,并获得所需的结果它会将整个文本打印到控制台。稍后我将对文件进行一些文本处理,子进程读取和处理,然后将更新的文本发送给父进程,但现在我只想确保我得到 pipe() 的基础知识是正确的。
示例文件:
This is a test file; it is 1 of many.
Others will follow.
相关代码:
pid = fork();
ifstream fin;
fin.open(inputFilename);
fin.get(inputChar);
if (pid == -1)
{
perror("Trouble");
exit(2);
}
else if (pid == 0) //child process that reads text file and writes to parent
{
close(pipefds[0]);
while(!fin.eof())
{
write(pipefds[1], &inputChar, sizeof(inputChar));
fin.get(inputChar);
}
close(pipefds[1]);
exit(0);
}
else
{
close(pipefds[1]);
read(pipefds[0], readbuffer, sizeof(readbuffer));
cout << readbuffer << endl;
close(pipefds[0]);
exit(0);
}
fin.close();
但是,当我编译和运行时,输出的长度总是不同的。有时它会打印整个文件,有时它只会打印几个字母或半行。比如。
This i
我已尝试浏览手册页并进行更多研究,但找不到任何答案。我的程序到底发生了什么,它有时会从文件中读取所有内容,但有时不会。非常感谢任何帮助!
【问题讨论】:
-
readbuffer是如何定义的? -
它是一个字符数组。
标签: c++ c linux system-calls