简体   繁体   中英

C - Redirect Standard Input/Output to a single, bidirectional file descriptor

In certain contexts, such as when dealing with a serial device file, I am able to open a bidirectional file descriptor. However, STDIN/STDOUT are two separate, unidirectional files. Is it possible to create a bidirectional file descriptor from STDIN/STDOUT? I ask for interface symmetry purposes: when writing user functions that need to both read and write , it is inconvenient to need to specify a file descriptor for both directions (only) when dealing with standard pipes.

There is a lot of discussion available about redirecting STDIN/STDOUT (for example using dup2 ), but this discussion is mostly concerned with piping input to/from subprocesses. I haven't found any information for combining two file descriptors into one.


EDIT: Here's the original context for the question. I don't care about solving this particular problem ; there are plenty of workarounds. I want to know about combining two unidirectional FDs into a single bidirectional one.

I am developing a C utility to control some fancy electronics over UART on Linux, and I would like to test the input/output of my code by using canned transactions from a file. That is, my mocked device responses will come from a text file that I create beforehand and pipe in through STDIN, while the sent commands will go to STDOUT and be saved to a file. This will allow transaction validation before connecting the real electronics, which could malfunction if mishandled.

[I'm not sure this will answer your question, and I was going to just put it as a comment, but it got too long.]

There are certainly many examples of "bidirectional" file descriptors in Unix and Linux -- serial ports and TCP streams pop immediately to mind.

If you have one of those, you can set up a process that both reads and writes to it (that is, that uses that one fd as both stdin and stdout) by using dup or dup2 to set it up as fd's 0, 1, and 2.

Finally, if you're a process and you believe you've been given a bidirectional fd as 0, 1, and 2, you can just grab 0, 1, or 2 and both read from and write to it (that is, write to 0 or read from 1).

But if fd's 0 and 1 aren't clones of each other, I don't know of a way to "combine" them into a single fd that permits both reading and writing.


Addendum: You mentioned the nuisance of carrying around two file descriptors if you're using a standard Unix pipe. I think the "bidirectional" alternative to a standard pipe would be a Unix-domain socket (evidently now called PF_LOCAL ).

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