在 C/C++我想多次写入同一个管道
我有一个程序可以在两个进程之间创建管道。一个进程不断监视另一个进程的输出,当遇到特定输出时,它使用 write() 函数通过另一个管道提供输入。但我遇到的问题是,在我 close()
管道之前,管道的内容不会进入其他进程的标准输入流。我希望这个程序能够无限循环,并在每次遇到它正在寻找的输出时做出反应。有没有办法在不关闭管道的情况下将输入发送到其他进程?
我搜索了一下,发现命名管道在关闭后可以重新打开,但我想知道是否还有其他选择,因为我已经编写了使用未命名管道的代码,而且我还没有学会使用命名管道。
I have a program that creates pipes between two processes. One process constantly monitors the output of the other and when specific output is encountered it gives input through the other pipe with the write()
function. The problem I am having, though is that the contents of the pipe don't go through to the other process's stdin stream until I close()
the pipe. I want this program to infinitely loop and react every time it encounters the output it is looking for. Is there any way to send the input to the other process without closing the pipe?
I have searched a bit and found that named pipes can be reopened after closing them, but I wanted to find out if there was another option since I have already written the code to use unnamed pipes and I haven't yet learned to use named pipes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看看如何使用 fflush。
Take a look at using fflush.
你读另一端怎么样?您期待完整的字符串吗?您没有在您发布的代码片段中发送终止 NUL。也许发送 strlen(string)+1 字节可以修复它。没有看到代码很难判断。
How are you reading the other end? Are you expecting complete strings? You aren't sending terminating NULs in the snippet you posted. Perhaps sending strlen(string)+1 bytes will fix it. Without seeing the code it's hard to tell.
使用fsync。 http://pubs.opengroup.org/onlinepubs/007908799/xsh/fsync.html
来自 http://www.delorie.com/gnu/docs/ glibc/libc_239.html:
一旦写入返回,数据就会排队等待写入并可以立即读回,但不一定会立即写出到永久存储。当您需要在继续之前确保数据已永久存储时,可以使用 fsync。 (对于系统来说,批量连续写入并在方便时一次性完成所有写入会更有效。通常它们总是会在一分钟或更短的时间内写入磁盘。)现代系统提供了另一个函数 fdatasync,它仅保证文件的完整性数据,因此速度更快。您可以使用 O_FSYNC 打开模式使 write 在返回之前始终将数据存储到磁盘。
Use fsync. http://pubs.opengroup.org/onlinepubs/007908799/xsh/fsync.html
From http://www.delorie.com/gnu/docs/glibc/libc_239.html:
Once write returns, the data is enqueued to be written and can be read back right away, but it is not necessarily written out to permanent storage immediately. You can use fsync when you need to be sure your data has been permanently stored before continuing. (It is more efficient for the system to batch up consecutive writes and do them all at once when convenient. Normally they will always be written to disk within a minute or less.) Modern systems provide another function fdatasync which guarantees integrity only for the file data and is therefore faster. You can use the O_FSYNC open mode to make write always store the data to disk before returning.