52

In Linux, is it possible for me to open a socket and pass the socket to another process? If yes, can you please tell me where I can find an example?

Thank you.

n179911
  • 19,547
  • 46
  • 120
  • 162
  • possible duplicate of [Can I share a file descriptor to another process on linux or are they local to the process?](http://stackoverflow.com/questions/2358684/can-i-share-a-file-descriptor-to-another-process-on-linux-or-are-they-local-to-t) – Gilles 'SO- stop being evil' Jan 01 '14 at 21:43
  • @Gilles'SO-stopbeingevil' you're linking to a auestion that was asked chronologically after this one how can it be a duplicate? – SpectreVert Jan 26 '22 at 14:31

1 Answers1

67

Yes you can, using sendmsg() with SCM_RIGHTS from one process to another:

SCM_RIGHTS - Send or receive a set of open file descriptors from another process. The data portion contains an integer array of the file descriptors. The passed file descriptors behave as though they have been created with dup(2).

http://linux.die.net/man/7/unix

That is not the typical usage though. More common is when a process inherits sockets from its parent (after a fork()). Any file handles (including sockets) not closed will be available to the child process. So the child process inherits the parent's sockets.

A server process that listens for connections is called a daemon. This usually forks on each new connection, spawning a process to handle each new request. An example of the typical daemon is here:

http://www.steve.org.uk/Reference/Unix/faq_8.html#SEC88

Scroll down to void process().

sehe
  • 374,641
  • 47
  • 450
  • 633
jspcal
  • 50,847
  • 7
  • 72
  • 76
  • 19
    Unless you don't want to fork a new process for every request but just pass the request on to a set of workers. – magiconair Apr 03 '11 at 14:35
  • This looks specific to AF_UNIX. Can this be done for TCP sockets? – Adrian Ratnapala Jan 11 '13 at 07:44
  • 14
    @AdrianRatnapala: no, you can't send a socket (or file handle) over TCP to another machine, they must stay within the same kernel. So the channel over which you communicate must be AF_UNIX, but the file handle you transfer can of course be a TCP socket. – Zarat Jan 14 '13 at 18:33
  • 2
    @Zarat, OK, good, naturally you can't send them across machines. I somehow got it into my head that only AF_UNIX sockets could be transferred. Stupid of me - the man page is actually perfectly clear. – Adrian Ratnapala Jan 19 '13 at 07:57
  • What if both of the processes are also reading from the socket what happens ? – Evren Bingøl Jan 08 '18 at 07:45
  • 1
    Another good example where socket is passed by a sentinel process to other processes is https://github.com/zimbatm/socketmaster – rajya vardhan Jul 12 '18 at 13:58