Monday, November 19, 2007

Because Polling Is Evil

Is this thing still here? Wow. Anyway, I like my job. I get to play with robots, and I have opportunities to learn a lot of new things (most of the tasks assigned to me are things I've never done before). Last week I learned how to write a daemon.

I had been asked to write a Linux program which would sample force-torque data from an ADC and then send it to another computer (via TCP). Doing the bare minimum didn't take all that long, once I stopped trying to use the buggy DAQ driver from the vendor (I won't name names, but it's a national company known for making various types of instruments) and went with libcomedi instead; but after I got it working with the functionality I'd been asked for, I decided to scrap that and do it the right way instead. (The original design had me doing things like transmitting floating point numbers as ASCII character strings and taking sample readings in response to polling from the client rather than at a steady frequency. Polling!)

In the process of making the deliverable awesomer, I decided it would be a good opportunity to work on my Unix system programming skills (which don't get exercised much when I'm doing Java stuff). So, first I read about getopt_long and had it parse command line arguments to (for instance) set the server port number and data collection frequency. Then after thinking about it some more, I decided that my server should act like a real server and have a name ending in "d", so I set to work daemonizing it (this came in handy). I redirected I/O to /dev/null, I replaced the verbose-mode printfs with calls to syslog, I gave it a .conf file which lives in /etc, and I gave it an init script so that my daemon would get launched automatically when the machine enters runlevel 2 (the kubuntu default). Oh, and a lockfile so that only one instance will run at a time. And I added the "d" to the end of its name. I'm quite happy with the result, and my project supervisor said, "You are the biggest geek I know. And that's saying something. Good work."

Of course, the guys I did this work for? The first thing they asked me to do was stop the daemon so they could run their slow buggy collect-data-and-save-to-a-file, regulate-collection-frequency-with-usleep program based loosely on the old version of mine. Oh well.