What are the portable options if one needs to export open file descriptors to child processes created using exec family of library functions?
Thank you.
EDIT. I know that child processes inherit open descriptors. But how they use those descriptors without knowing their values? Should I implement some sort of IPC in order to pass descriptors to the child process? For example, if the parent creates a pipe, how can an execed child process know read/write ends of the pipe?
Simply don’t set the
O_CLOEXECopen(2)flag or its corresponding (and standard)FD_CLOEXECfcntl(2)flag on the descriptor — it’ll be passed across anexec*()by default.Update
Thanks for the clarification, that does change things a little bit.
There are several possibilities:
Use command line arguments: GnuPG in
gpg(1)provides command line switches--status-fd,--logger-fd,--attribute-fd,--passphrase-fd,--command-fdfor each file descriptor that it expects to receive. If there are several kinds of data to submit or retrieve, this lets each file descriptor focus on one type of data and reduces the need for parsing more complicated output.Just work with files and accept filenames as parameters; when you call the program, pass it file names such as
/dev/fd/5, and arrange for the input to be onfd5before calling the program:Follow conventions: supply
0to the child as the read end of a pipe,1to the write end of a pipe, and let it work as a normal pipeline “filter” command. This is definitely the best approach if all the input can be reasonably sent through a single file descriptor — not always desirable.Use an environment variable to indicate the file / socket / fd:
This is nice to pass the file information through many child programs.