Jacob Kaplan-Moss

Python is Unix

I wrote this post in 2009, more than 14 years ago. It may be very out of date, partially or totally incorrect. I may even no longer agree with this, or might approach things differently if I wrote this post today. I rarely edit posts after writing them, but if I have there'll be a note at the bottom about what I changed and why. If something in this post is actively harmful or dangerous please get in touch and I'll fix it.

Ryan Tomayko’s I like Unicorn because it’s Unix should be required reading for anyone doing anything involving networks or unixes these days. Like Ryan, I share a deep appreciation for the dark art of Unix system calls, and like Ryan I’m a bit dismayed to see them relegated to the dusty corners of our shiny dynamic languages.

So I read I like Unicorn because it’s Unix with glee; it’s perhaps the cleanest, clearest explanation of how preforking socket servers work, and I enjoyed seeing Ruby’s twist on the old standard.

Since I’m a Python hacker, though, and since I had a couple minutes, I thought it’d be an interesting exercise to port Ryan’s code to Python. So, with no further ado, here we go:

I’ve tried to keep the control flow the same as the original, even going so far as to copy some of Ryan’s comments verbatim so you can see what matches up, and what doesn’t.

Update:

As suggested in the comments, I’ve written a more Pythonic version would use Python’s built-in SocketServer library. I still prefer the above for didactic purposes: it does a much better job showing off the low-level concepts and system calls.

There’s some interesting differences – Ruby’s use of a block to differentiate the forked child is beautiful – but the important takeaway is that this stuff is easy in any modern programming language. If you do stuff on the ’net, you should know this POSIX stuff.

Dunno about you, but I’m going to spend my evening reading Unicorn. Looks like there’s lots of nifty stuff to learn there.