有没有一种简单的方法可以清除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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“清除”管道的方法是从管道中读取数据,直到缓冲区为空。这对你没有帮助。我猜测您真正的问题是父级可能会读取来自多个客户端的混合数据。有两种简单的解决方案可以解决您的问题。
始终写入长度小于
PIPE_BUF
字节的消息,并在一次调用write
中执行此操作。这将确保对管道的写入是原子的。为每个子进程使用单独的管道。在服务器端,可以使用线程,也可以使用带有
select
或poll
的非阻塞 IO。同样,您可以使用 Unix 域套接字,并让每个客户端连接到该套接字(这实际上只是创建单独管道的不同方式)。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.
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.Use a separate pipe for each child process. On the server side, either use threads or use nonblocking IO with
select
orpoll
. 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).