Search code examples
erlangerlang-otp

Processes with unidirectional links


I need to create processes with unidirectional links. Say I have three linked processes

grandparent <- parent <- child

The processes do their job and die, but are blocked by the processes generated by them. When the child dies, the parent and grandparent also die, but not the other way around. The toy example would be processed that just create children and wait for them to die:

(init)
(wait) <- (init)
(wait) <- (wait) <- (init)
(wait) <- (wait) <- (die)
(wait) <- (die)
(die)

For the example not to be infinitely recursive, let's say that each process has only one job: on (init) it tosses a coin, on heads it spawns a child process, or on tails, it dies.

What is the nice way of doing this in Erlang/OTP?


Solution

  • Each parent should monitor its immediate children (for example, using spawn_monitor.

    When a monitored process dies, the VM sends a {'DOWN', MonitorRef, process, Pid, Info} message to the monitoring process, then the monitoring process can just exit or throw an error.

    E.g:

      {Pid, MonitorRef} = spawn_monitor(?MODULE, child, []),
      receive {'DOWN', MonitorRef, process, Pid, Info} -> exit(Info) end.