简体   繁体   中英

Is using streams over pipes under Linux worthwhile?

在Linux下使用管道在进程之间进行通信时,使用fdopen从管道创建流,然后在流上使用fread / fwrite代替read / write有什么好处?

Standard Input/Output (stdio)

fdopen is part of the stdio library. From stdio manual , you get this:

The standard I/O library provides a simple and efficient buffered stream I/O interface. Input and output is mapped into logical data streams and the physical I/O characteristics are concealed. The functions and macros are listed below; more information is available from the individual man pages.

And then:

The stdio library is a part of the library libc and routines are automatically loaded as needed by the compilers cc(1) and pc(1) . The SYNOPSIS sections of the following manual pages indicate which include files are to be used, what the compiler declaration for the function looks like and which external variables are of interest.

Being part of the libc , it means that programs written using these functions will compile in all standard-conforming compilers. If you write a program using open/write (which are POSIX ), then your program will only run on POSIX systems.

So you could reason that (a) it's worth because of portability and (b) it's not worth it if you're only using it in Linux, because then using open/write you remove a whole lot of abstraction (from stdio) - keep in mind that under GNU GLibC open/write are wrappers around the syscalls, you're not actually calling then directly, so a small amount of abstraction is present.

Writing into a pipe involves a syscall and a context switch. If you would like to minimize these, you may like to use stdio functions to do buffering in the user space, and this also allows for formatted output with fprintf .

A FILE* created out of a file descriptor using fdopen() will provide the additional features of buffering, error checking ( feof() , ferror() ) etc which you may or may not need. I don't see any benefit of using a fdopen() mainly because the pipe itself will do certain level of buffering (on modern Linux, it's 64K). Besides, in most use-cases where pipes are used in IPC , buffering isn't desirable.

So, I don't see any benefit of using fdopen() . Using read() & write() directly will be sufficient and often desirable in IPC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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