简体   繁体   English

阅读/写入管道是一项昂贵的操作吗?

[英]Is reading/writing to a pipe an expensive operation?

As part of my Uni course we've been shown and asked to use pipes to communicate between processes (using pipe() and fork() ) for a few small exercises. 作为我的Uni课程的一部分,我们已经被展示并被要求使用管道在进程之间进行通信(使用pipe()fork() )进行一些小练习。 No problems getting it to work or with the concept, but outside of these requirements I'm wondering how efficient it is to write and read with a pipe of this type? 没有问题让它工作或与概念,但在这些要求之外,我想知道用这种类型的管道写和读的效率如何?

If I've some value that I'm packing in to a block of 4 bytes, is it better to pack and write 100 values (so 400 bytes) all at once? 如果我有一些值,我正在打包到一个4字节的块,是不是一次打包并写入100个值(所以400字节)?

Or is the performance comparable if I do 100 writes each of 4 bytes? 或者,如果我每次写入4个字节,那么性能是否可比?

Does piping 400 bytes in one go prevent the reciever doing anything until the write is complete - assuming the reciever is only trying to read the first 4 bytes, will it be able to do so after they're written, but before all 400 is finished? 一次性管道400字节是否阻止接收器执行任何操作,直到写入完成为止 - 假设接收器只是尝试读取前4个字节,是否能够在写入之后但在所有400个字节完成之前执行此操作?

Pipes are handled similarly to files (of course, they're not on the disk). 管道的处理方式与文件类似(当然,它们不在磁盘上)。 They are buffered in some same ways, and the handle to them is treated similarly. 它们以相同的方式缓冲,并且对它们的句柄进行类似处理。 Don't try to manually buffer for a pipe; 不要尝试手动缓冲管道; it does that already. 它已经这样做了。 If you're really concerned about it, you could try both ways and collect some run times. 如果您真的关心它,您可以尝试两种方式并收集一些运行时间。 I'd suggest just writing blocks of 4 bytes as you have them. 我建议你只需要编写4个字节的块。 Don't try to optimize unless you know there's a problem. 除非您知道存在问题,否则不要尝试优化。

I can tell you an anecdote. 我可以告诉你一个轶事。 I once worked on a web system for an embedded Linux platform. 我曾经在一个嵌入式Linux平台的Web系统上工作过。 We tried pipes for internal communication, because they were much faster than UNIX socket or TCP sockets. 我们尝试使用内部通信管道,因为它们比UNIX套接字或TCP套接字快得多。 In the end we used sockets anyway, because they were simpler to use in our application. 最后我们还是使用了套接字,因为它们在我们的应用程序中使用起来更简单。 (We needed two-way communication and pipes are only one way.) (我们需要双向沟通,管道只有一种方式。)

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

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