Dave Vogt
Dave Vogt

Reputation: 19582

Let a supervisor die if a child exits

(Note: I'm still learning, and the following may thus be a completely stupid architecture)

I'm building a simple TCP server in Erlang. I have a hierarchy that starts a supervisor for each peer connection, which in turn oversees a multiplexer, a socket reader and a socket writer.

Now of course when the client socket closes, all four (supervisor, mux, reader, writer) should exit, as it doesn't make sense for them to stay around. The reader/writer do note when the socket closes and exit, but the supervisor still hangs around.

How do I setup the supervisor so that this happens?

Upvotes: 1

Views: 221

Answers (1)

legoscia
legoscia

Reputation: 41648

You can set the supervisor's "maximum restart frequency" to zero, meaning that the supervisor will crash if any of its children crashes. The init function of the supervisor module would look something like this:

init(Args) ->
    Multiplexer = #{id => multiplexer, start => ...},
    Reader = #{id => reader, start => ...},
    Writer = #{id => writer, start => ...},

    Flags = #{intensity => 0},
    {ok, {Flags, [Multiplexer, Reader, Writer]}}.

For cases like this, when a supervisor supervises processes that are tightly coupled and should be restarted together, you'd normally use the one_for_all restart strategy, but here it doesn't matter since you just want the entire thing to crash.

Upvotes: 5

Related Questions