有没有一种简单的方法来清除C中的管道 [英] Is there an easy way of clearing a pipe in C
问题描述
我有一个所有子进程都使用的管道,但是在子进程使用该管道与父进程对话之前,我需要清除它,以便父进程正确地读取它. C中有一个简单的函数可以做到这一点吗?
I have a pipe that all my child processes use, but before a child uses the pipe to talk to the parent I need to clear it so that the parent reads from it correctly. Is there a simple function in C to do this?
推荐答案
清除"管道的方法是从管道中读取直到缓冲区为空.这对您没有帮助.我猜您真正的问题是父级可能读取来自多个客户端的数据.解决您的问题有两种简单的方法.
The way to "clear" a pipe is to read from it until the buffer is empty. This doesn't help you. I am guessing that your real problem is that the parent might read data that is mixed from multiple clients. There are two easy solutions to your problem.
-
总是写少于
PIPE_BUF
个字节长的消息,并在一次调用write
的情况下执行此操作.这将确保对管道的写入是原子的.
Always write messages less than
PIPE_BUF
bytes long, and do this in a single call towrite
. This will ensure that writes to the pipe are atomic.
为每个子进程使用单独的管道.在服务器端,使用线程或将非阻塞IO与select
或poll
一起使用.同样,您可以使用Unix域套接字,并让每个客户端都连接到套接字(这实际上是创建单独管道的另一种方式).
Use a separate pipe for each child process. On the server side, either use threads or use nonblocking IO with select
or poll
. Equivalently, you could use a Unix domain socket, and have each client connect to the socket (this is really just a different way of creating the separate pipes).
这篇关于有没有一种简单的方法来清除C中的管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!