Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

Check out Erlang documentation: http://www.erlang.org/doc/design_principles/sup_princ.html

All you have to do is to rearrange you process-tree and use one_for_all restart strategy. In my oppinion Child1 and Child2 should be children of Supervisor.

Or, in case you want to keep things like they are at the moment you have to catch EXIT of process Child2 in process Child1. When EXIT comes to Child1 all Child1 has to return is:

{stop, normal, State}

and it will be automaticall restarted by Supervisor. Supervisor must be in permanent restart mode.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top