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 (, you need to add these two functions to it’s implementation

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

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

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


You can also add a stop API hook:

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

def handle_call(:stop, _, state) do
  #pre-stop things
  {:stop, :normal, reply, state}

Note that calling GenServer.stop will bypass this so you have options about where you want to put your stopping cleanup logic.

1 Like

The cheatsheet is especially helpful.

After solving the problem I asked about, I still had other issues to solve and this cheatsheet got me thru it. Many thanks.

1 Like