2011-09-07

Careful with closing file descriptors!

These days I was having a very very odd problem with a server implemented with onion. It was redirecting the stderr to the web connections!

At first I thought some weird file descriptor shuffle that was assigning the wrong descriptor 2, stderr, to the connection. I thought a lot about what could make this happen, checked a lot of code a couple of times and nothing.

Finally, after several days with that problem over my head I thought... ok maybe I'm thinking it wrong.. maybe its the stderr that gets into another connection, but that could not happen as its forcefully the descriptor nr 2... unless... that descriptor were free for the socket assignment and it were writing to an invalid descriptor normally and when the descriptor nr 2 is assigned by chance I write something on stderr. And that was it.

The script to start the server was closing the descriptors (thanks to an older code that redirected that output to a file, and then we decided it wasn't necessary). So when starting my program, descriptor 2 was free, and 1. So normally one connection goes to nr 1, and second simultaneous connection went to 2:

# close 1 and 2
exec 1<&-
exec 2<&-
# redirect to www.log
#exec 1>/var/log/www.log
#exec 2>
/var/log/www.log
./botserver &

A bit complicated problem, but simple solution, redirect it to /dev/null. I was really happy it was not a bug into onion, but from the caller.

So the final line: when closing stdout and stderr, think who gets it. Maybe they expect they are stderr and stdout, and will use one of your descriptors for their legitimate function.

No comments:

Post a Comment