Signals in Haskell

When playing with Haskell I sometimes get the feeling that I’m the last one in the world to figure out how some things work. It’s almost embarrassing to write about it at times, but I fear I’ll forget and end up redoing my trivial experiments if I don’t ((Or maybe I shouldn’t compare myself to the highly (dare I say it?) academical entries usually found on the Haskell Planet. Maybe I should just consider my writing to be “Haskell for mortals”.)). So, here goes…

Dealing with signals in Haskell is fairly straight forward. Well, at least as far as dealing with signals ever is straight forward. In System.Posix.Signals you find installHandler. The arguments are a little funky but they get a little clearer if you look up the man-page for sigaction.

Here’s a simple example that installs a handler for SIGINT:

Now that’s fairly straight forward, I think. However, it’d be nice to be able to let the main thread know that we’ve recieved a signal in some way. From perusing the Haskell Wiki it seems the way to communicate between threads, at least for simple cases, is by using MVars. So, extending the example above to also keep track of how many times SIGINT has been received could look like this:

It should be noted that, and here it all hinges on me having understood things correctly, handler has more or less become a sort of critical section. Taking the value out of the MVar makes sure that the readMVar in doNothing blocks until a new value is put back. Probably not a very useful thing in this particular example, but it’s still worth keeping in mind for the future.

⟸ Unescaping URLs in Python and Haskell Types are funky... ⟹

Dominique Valentine

I enjoy your blog.

Magnus

Thanks, Dominique.

Leave a comment