Search code examples
erlangbehaviorspawnerlang-supervisor

supervising child process of restarted process


I have a structure like this

-------------
|Supervisor |
-------------
      |
-------------
|  Child1   |
-------------
      |
-------------
|  Child2   |
-------------

In this structure, child1 is supervised and it spawns child2. What I need is to be able to restart child1 when child2 crashes/exits. Which would be the best way to achieve this?


Solution

  • If you allow Child1 to crash when Child2 crashes, your existing supervisor will simply restart Child1, thus also restarting Child2.

    But that depends upon Child1 crashing when Child2 crashes. Another option is to insert another supervisor in the process tree:

    Change this:                          Into this:
    
    +------------+                      +------------+
    | Supervisor |                      | Supervisor |
    +------------+                      +------------+
          |                                   |
    +------------+                      +------------+
    |   Child1   |  New supervisor ---> | Supervisor |
    +------------+                      +------------+
          |                               |      |
    +------------+              +------------+ +---------+
    |   Child2   |              |   Child1   | |  Child2 |
    +------------+              +------------+ +---------+
          |                                        |
     other service                            other service
    

    The new supervisor handles just the two children as their own service, allowing the death of either one to influence the other in configurable ways.