How to kill child process under DynamicSupervisor

Most tutorials on this seem outdated. I hunted thru the hexdocs on DynamicSupervisor and GenServer, but I find it all very confusing.

This example seems to work for me just fine, and was really helpful, but it doesn’t show how to kill my child process by name. How do I do that?

Your child in the supervisor iis just a GenServer (or something that builds upon it). So you can stop it just as you do with GenServer.

Via GenServer cheatsheet (https://elixir-lang.org/cheatsheets/gen-server.pdf), you need to add these two functions to it’s implementation

``````def stop(pid, reason \\ :normal, timeout \\ :infinity) do
GenServer.stop(pid, reason, timeout)
end

def terminate(reason, state) do
# perform cleanup
# result will not be used
end
``````

And call it with `reaason` set to `:normal` so the process will not get restarted by `DynamicSupervisor`.

3 Likes

You can also add a stop API hook:

``````def stop(who), do: GenServer.call({:via, Registry..., :stop)

def handle_call(:stop, _, state) do
#pre-stop things