Phillip Pearson - web + electronics notes

tech notes and web hackery from a new zealander who was vaguely useful on the web back in 2002 (see: python community server, the blogging ecosystem, the new zealand coffee review, the internet topic exchange).


UNIX hackery: passing file descriptors

I've only recently found out about some of the cleverer things you can do in UNIX-like systems (e.g. Linux and BSD). Passing file descriptors is one of them.

What is going on here is that you have a bunch of different processes running on your system. One of them opens a file, and wants to let another one have it. Perhaps the other one isn't able to open the file because it doesn't have permission, or perhaps it's something transient -- for example, process #1 could have just accepted an incoming connection on a socket, and it doesn't exist in the filesystem, so process #2 can't even see it.

If the two processes are communicating over some sort of socket, you can pass the file descriptor between them. Here's a good explanation, from the postfix archive, of how to actually do it. Basically you use the sendmsg function with a special flag that lets the kernel know you are sending a file descriptor, and it will duplicate the descriptor and give it to the target process. Very handy.

This is useful when writing network servers, because you can have a bunch of worker processes that accept socket descriptors that are passed from one 'master' server that accepts connections on a socket. Makes it easier to separate programs out, which can be good for security and performance.

Here's something from Kragen Sitaker that accepts socket connections then passes them off to another app for processing. The idea here is to make the program as secure as possible by minimising the amount of code that needs to run as the superuser.
... more like this: [, ]