有没有一种简单的方法来清除C中的管道

编程入门 行业动态 更新时间:2024-10-25 01:21:53
本文介绍了有没有一种简单的方法来清除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 to write. 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中的管道

    本文发布于:2023-10-27 23:36:33,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1534863.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:方法来   管道   简单

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!