-
Forcing a Code Update in a Running Erlang Process
2007-11-23 23:10 in /tech/erlang
A couple days ago I wrote my first IRC bot, to echo updates from an RSS feed into an IRC channel. It seemed like a fun thing to do in Erlang, and the bot ended up being basically a splice of Jonathon Roes’ bot skeletor with Sam Ruby’s post about parsing Atom.
While I was writing the bot I put in lots of debugging statements, but once it was running nicely, they were a bit tiresome. Of course, I could have simply stopped the bot, removed the statements, and restarted it; but this is Erlang and hot code updates are one of the heavily advertised features. The relevant docs explain how to load new code versions which will be picked up by new processes, but don’t really address how to update an already running process. I asked on #erlang and got the pointer to add a message to the main server loop for doing a code upgrade. This calls
?MODULE:loop
rather than simplyloop
, which turns it into an “external function call” and allows the new code version to be used. So, now my main loop looks like:loop(Sock, Seen) -> receive code_upgrade -> ?MODULE:loop(Sock, Seen); {tcp, Sock, Data} -> io:format("[~w] Received: ~s", [Sock, Data]), parse_line(Sock, string:tokens(Data, ": ")), loop(Sock, Seen); ...
And I can update the running code by just doing:
> c("bot.erl"). > Bot ! code_upgrade.
(Aside: I’m a little curious about how hot code loading and tail recursion work together. When I call
?MODULE:loop
after an upgrade, it seems like the normal tail-call optimization shouldn’t work. I suspect there’s something clever going on to take care of this, though.)
Leave a comment
Please use plain text only. No HTML tags are allowed.