为什么在使用 ifstream 读取命名管道的一行后得到 EOF? [英] Why do I get EOF after reading one line thourgh a named pipe using ifstream?

查看:83
本文介绍了为什么在使用 ifstream 读取命名管道的一行后得到 EOF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在命令行中,我使用 mkfifo 创建了一个管道并确认该文件存在.ls -al 给出:

At the command line I used mkfifo to create a pipe and confirmed that the file existed. ls -al gives:

prw-r--r--    1 user  group      0 Mar 30 11:52 my_pipe

然后我使用此代码尝试从该管道中逐行读取文本:

I then use this code to attempt to read text line by line from that pipe:

ifstream pipe("/path/to/my_pipe");
string message;
while(getline(pipe, message) && message != "EXIT")
{
    cout << boolalpha << pipe.good() << endl << pipe.eof() << endl << pipe.bad() << endl;
}

cout << boolalpha << pipe.good() << endl << pipe.eof() << endl << pipe.bad() << endl;

回到命令行我做 echo "banana" >my_pipe 然后程序存在,输出如下:

Back to the command line I do echo "banana" > my_pipe and then the program exists with the following output:

true
false
false
false
true
false

这表明在读取 banana 后流处于良好状态,但在第二次调用 getline 时我点击了 EOF 和退出.

This would indicate that the stream was in a good state after reading banana but that in the second call to getline I hit EOF and exited.

为什么我点击了 EOF,我可以做些什么来保持流阅读并保持良好状态,直到我阅读我的特殊 EXIT 消息?

Why did I hit EOF and what can I do to keep the stream reading and in a good state until I read my special EXIT message?

结论:

  1. 使用 fstream 而不是 ifstream.
  2. 在撰写本文时,libc++ 中显然存在一个关于 fstream 和管道的错误.

推荐答案

当管道被所有打开以进行写入的进程关闭时,会在管道上发生 EOF.在您的示例中,打开它进行写入的唯一进程是 echo 命令;退出时,关闭管道,导致读取过程中出现EOF.

EOF occurs on a pipe when it's closed by all the processes that have it open for writing. In your example, the only process that opens it for writing is the echo command; when it exits, , it closes the pipe, which results in EOF in the reading process.

如果您希望管道在每个客户端写入它之间保持打开状态,那么这样做的方法是以读写模式打开管道.这样,读的过程也将是写的过程,只要管道打开,它就永远不会被所有的写者关闭.

If you want the pipe to stay open between each client writing to it, the way to do it is to open the pipe in read-write mode. That way, the reading process will also be a writing process, and as long as it has the pipe open it will never be closed by all the writers.

fstream pipe("/path/to/my_pipe");

或者,您可以通过在单个重定向进程中执行多个命令来保持发送端的管道打开:

Alternatively, you can keep the pipe open on the sending side by executing multiple commands within a single redirected processes:

( echo banana ; echo EXIT ) > my_pipe

这篇关于为什么在使用 ifstream 读取命名管道的一行后得到 EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆