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.

2

1 Answer 1

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().

6
  • 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 3, 2011 at 14:35
  • This looks specific to AF_UNIX. Can this be done for TCP sockets? Jan 11, 2013 at 7: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, 2013 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. Jan 19, 2013 at 7:57
  • 1
    Another good example where socket is passed by a sentinel process to other processes is github.com/zimbatm/socketmaster Jul 12, 2018 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.