Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable way to pass file descriptor between different processes

Tags:

On most UNIX systems passing an open file between processes can be easily done for child/parent processes by fork(); however I need to share a fd "after" the child was already forked.

I've found some webpages telling me that sendmsg() may work for arbitary processes; but that seems very OS dependent and complex. The portlisten seems like the best example I can find, but I'd prefer a good wrapper library like libevent that hides all the magic of kqueue, pool, ....

Does anyone know if there's some library (and portable way) to do this?

like image 311
Francis Avatar asked May 26 '09 05:05

Francis


People also ask

Can file descriptors be shared between processes?

File descriptors are generally unique to each process, but they can be shared by child processes created with a fork subroutine or copied by the fcntl, dup, and dup2 subroutines.

How do you pass file descriptor?

Named streams are useful for passing file descriptors between unrelated processes on the same machine. A user process can send a file descriptor to another process by invoking the I_SENDFD ioctl(2) on one end of a named stream.

Do child processes inherit file descriptors?

The fork SubroutineCreates a child process that inherits the file descriptors assigned to the parent process.

Does each process have its own file descriptor table?

The file descriptor table itself contains pointers to the file objects which do all the resource handling. Each process (a process being an instance of an application) has it's own file descriptor table which is pointed to by an entry in it's process description table.


2 Answers

Your best bet is to try sending the file descriptor over a Unix domain socket. This is described in Stephens, and in a few places on the web, but I can dig up code for you if you ask nicely.

This will be pretty portable these days; a lot of the things considered "non-portable" way back when (such as mmap!) are extremely common now. If you need to be more portable than "most systems these days," you've got a lot of interesting issues ahead of you, but possibly if you tell us more about what you're doing and what platforms you're working on (perhaps non-Unix POSIX platforms?) we might be able to help out.

like image 194
cjs Avatar answered Sep 26 '22 08:09

cjs


There is a Unix domain socket-based mechanism for transferring file descriptors (such as sockets - which cannot be memory mapped, of course) between processes - using the sendmsg() system call.

You can find more in Stevens (as mentioned by Curt Sampson), and also at Wikipedia.

You can find a much more recent question with working code at Sending file descriptor by Linux socket.

like image 23
Jonathan Leffler Avatar answered Sep 26 '22 08:09

Jonathan Leffler