26

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Francis
  • 11,388
  • 2
  • 33
  • 37
  • 1
    Search for "File Descriptor Passing" on [Demystifying Unix Domain Sockets](http://www.techdeviancy.com/uds.html) – mgalgs Jun 20 '17 at 17:28

2 Answers2

18

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.

Lothar
  • 12,537
  • 6
  • 72
  • 121
cjs
  • 25,752
  • 9
  • 89
  • 101
  • 1
    I still have a question in using the sendmsg(). I thought putting domain socket as the first parameter is enough, but seems like I still have to fill the msghdr.msg_name as the sockaddr_un of the domain socket - why? anyway to prevent it? – Francis May 26 '09 at 18:33
13

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.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278