How to identify if a process is being spawned or restarted?

I have a FIFO queue of processes, whenever a process dies it must be removed from the queue.

When a process is spawned by the DynamicSupervisor, it register itself on the rear of the queue.

When a process is restarted by the DynamicSupervisor, it should register itself on the front of the queue instead of the rear.

Therefore I need a way to identify on the process init/1 function if the process is being spawned or restarted.

I thought about some approaches to this problem:

  • Keep some state outside the process being restarted (ETS table maybe?) to track where the process should be registered
  • Overwrite the supervisor restart_child/2 function to inject some data

I do not know if there is a simpler way to achieve this behaviour, what’s your thoughts?

A similar question has been asked before - How can I monitor when a process is restarted. I don’t know the right solution but the thread might be helpful.

1 Like

You can monitor death of a process, and turn a restart flag on, before the init of the restarted process.

By the way You should use handle_continue to make initialization, instead of init, if it takes some time.

There is a good example of pool in the little book of Elixir/OTP