简体   繁体   English

在C / C ++中,我想多次写入同一管道

[英]In C/C++ I want to write to the same pipe multiple times

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. 一个进程会不断监视另一个进程的输出,当遇到特定输出时,它将使用write()函数通过另一个管道提供输入。 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. 我遇到的问题是,在我close()管道之前,管道的内容不会传递到另一个进程的stdin流中。 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. 我进行了一些搜索,发现在关闭命名管道后可以重新打开它们,但是我想知道是否还有其他选择,因为我已经编写了使用未命名管道的代码并且还没有学会使用命名管道。 。

看看使用fflush

How are you reading the other end? 您如何阅读另一端? Are you expecting complete strings? 您是否需要完整的字符串? You aren't sending terminating NULs in the snippet you posted. 您不会在您发布的代码段中发送终止NUL。 Perhaps sending strlen(string)+1 bytes will fix it. 也许发送strlen(string)+1个字节可以解决它。 Without seeing the code it's hard to tell. 没有看到代码,很难说。

Use fsync. 使用fsync。 http://pubs.opengroup.org/onlinepubs/007908799/xsh/fsync.html 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. 来自http://www.delorie.com/gnu/docs/glibc/libc_239.html :一旦写入返回,数据就排队待写入并可以立即读回,但是不一定要写到永久存储中立即。 You can use fsync when you need to be sure your data has been permanently stored before continuing. 在需要确保数据已永久存储然后继续之前,可以使用fsync。 (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. (对于系统而言,批处理连续的写操作并在方便时一次完成所有写操作效率更高。通常,它们总是在一分钟或更短的时间内写入磁盘。)现代系统提供了另一个功能fdatasync,它仅保证文件的完整性数据,因此速度更快。 You can use the O_FSYNC open mode to make write always store the data to disk before returning. 您可以使用O_FSYNC打开模式使写入操作始终将数据存储在磁盘上,然后再返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM