Eng.Fouad
Eng.Fouad

Reputation: 117587

Passing file-descriptors between processes asynchronously

I am implementing a web server where I need to make the parent process do the following:

and the worker process will do the following:

After looking around and searching the internet, I found that I can send a file descriptor between different processes via UNIX Domain Socket or Pipes. But unfortunately, I can do this synchronously only! (I can send one fd at a time, and I cannot put it in a waiting queue)

So, my question is:

Upvotes: 0

Views: 4633

Answers (2)

unwind
unwind

Reputation: 399823

File descriptors are just integers. They are used to index into a per-process table of file information, maintained by the kernel. You can't expect a file descriptor to be "portable" to other processes.

It works (somewhat) if you create the files before calling fork(), since the file descriptor table is part of the process and thus clone()d when the child is created. For file descriptors allocated after the processes have split, such as when using accept() to get a new socket, you can't do this.

UPDATE: It seems there is a way, using sendmsg() with AF_UNIX sockets, see here for details as mentioned in this question. I did not know that, sounds a bit "magical" but apparently it's a well-established mechanism so why not go ahead and implement that.

Upvotes: 2

Useless
Useless

Reputation: 67733

  1. put the fd on an internal queue (lock-free if you want, but probably not necessary)
  2. have a thread in the parent process which just reads an fd from the internal queue, and sends it via the pipe
  3. all child processes inherit the other end of the pipe, and compete to read the next fd when they finish their current job

Upvotes: 0

Related Questions