How attached are you

I don’t want to live when you die

Mark Nijhof
Functional Erlang
Published in
3 min readJun 13, 2013

--

I explained in my previous Erlang post that processes are like Lemmings, cheap and good for doing one thing. Like classes should be in an OO language.

Another great feature of Erlang is that it is designed to crash (much more on that later for sure). So your little processes may die at anytime and sometimes that is fine because you don’t care too much about that process anyway.

But other times you care a lot about that little process and if it dies you want to know, maybe even die yourself.

To link

And in Erlang you can! When you start a new process you decide whether the process that starts it should be linked to it or not. Which basically means that when either the “parent” process or the “child” process dies the other-one dies as well.

And that is great behavior, because often you rely on this other process and if it is not there your own function is impaired. In Erlang this would tie together whole trees of processes.

To unlink

There are always cases that you used to love a little process, but time changed things and now you couldn’t care less. In Erlang when that happens you can choose to unlink yourself from that other process. When you do that you won’t be sent an announcement.

To supervise

So it crashes and then what? Well that is why Erlang has Supervisors, their responsibility is to monitor child processes. And when a child process dies the supervisor will restart it.

It would do this for a predetermined number of times, if after that the child still crashes then the supervisor itself will crash as well.

There are two way for a supervisor to manage its children; “one on one” and “one for all”.

One on one

In this scenario, when one child dies the supervisor will restart just that child.

One for all

And in this case, when one child dies the supervisor will kill the other children and then restart all children. This case sounds a bit icky, but it is ideal when there is a tight relation between the different children.

To supervise the supervisor

Supervisors are like any other process and can be supervised by other supervisors as well. With this combination you can create very resilient process trees.

This also enables you to; at the start of your program create a supervisor to monitor the main process, and this main process can also monitor the supervisor. This way when the main process dies the supervisor will restart it, but then the supervisor dies the main process will restart that.

In this scenarion you will have to kill both processes simultaneously or else your program will not stop. It is easier to kill the VM :-)

Photo credit: source

--

--