使用管道进行进程间通信
我想也许这是一个显而易见的问题,但我只是想通过问你们来确定。
我正在使用管道系统调用来创建未命名管道来进行父子进程通信。
我的子进程需要收集一些信息并将其发送给其父进程。我的问题是:
- 我只能使用写入和读取函数发送和接收字符串吗?我必须忘记发送结构。
- 如果我上一个问题的答案是“是”,那么将所有信息传输到父进程的正确方法是多次调用函数 write 和 read ?
非常感谢!
I think maybe this is an obvious question, but I just want to be sure by asking you guys.
I'm working with parent-child process communication using the pipe system call to create a unnamed pipe.
My child process needs to gather some information and send it to its parent. My questions are:
- Can I only send and receive strings using the write and read functions, right? I have to forget about sending structures.
- If the answer to my previous question is "yes", the right way to transfer all the information to the parent process is to call the functions write and read several times?
Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以使用 write() 和 read() struct 就可以了;使用指向 struct 的指针作为 buf 参数。当您想要在不在同一台计算机上运行的进程之间执行此操作时,您就会遇到问题,并且需要对可移植表示进行编组/解组,以确保在任何地方都以相同的方式理解这些值。这包括识别数据“数据包”的开始和结束,因为管道实际上没有数据包的概念:如果您所做的只是编写一系列相同的
struct
,那么您只需write()
即可,读者可以依靠read()
返回 0 来指示该系列的结束;但是如果您还需要发送其他信息,那么您将需要一个框架协议来表示“接下来是这样那样的struct
”,“接下来是一个字符串”等。You can
write()
andread()
struct
s just fine; use a pointer to thestruct
as thebuf
parameter. It's when you want to do this between processes not running on the same machine that you run into problems and need to do marshaling/unmarshaling to portable representations to insure the values are understood the same way everywhere. This includes recognizing the start and end of data "packets", since a pipe doesn't really have the concept of packets: if all you're doing is writing a series of identicalstruct
s, then you can justwrite()
them and the reader can rely onread()
returning 0 to indicate the end of the series; but if you need to send other information as well then you'll need a framing protocol to say "what follows is such-and-suchstruct
", "what follows is a string", etc.