Monitoring after exit.. Hm

Hi! In the guides, chapter related to supervisors, I have met this test:

test "removes bucket on crash", %{registry: registry} do
  KV.Registry.create(registry, "shopping")
  {:ok, bucket} = KV.Registry.lookup(registry, "shopping")

  # Stop the bucket with non-normal reason
  Process.exit(bucket, :shutdown)

  # Wait until the bucket is dead
  ref = Process.monitor(bucket)
  assert_receive {:DOWN, ^ref, _, _, _}

  assert KV.Registry.lookup(registry, "shopping") == :error
end

Why are we sure at the Process.monitor(bucket) call bucket’s pid still keeps a value related to existing process?

If you try to monitor a PID that has already died then the monitor immediately dies in turn. :slight_smile:

Sorry, can not understand your comment. It is a fragment from official guide. I’m just curious if the code correct.

Yep, it is fine. A monitor will monitor a PID until it dies then report the death, if it is already dead then it reports that, therefore there is no race condition or issue that you might experience where a process died before you could monitor it. :slight_smile:

1 Like

So, if some pid is a pid of a process being dead during an age, a monitor will nevertheless send a :DOWN message to the current process. Not obvious. Thanks!

Yep that is it exactly, and I’d think it would be obvious, a ‘monitor’ monitors something, if it is monitoring something that is dead I’d expect it to say ‘uhh, why did you pass me a corpse?’. :-V

He-he. Now I also tend to treat this behaviour as obvious :slight_smile:

1 Like

The Elixir doc for monitor/1 links to the Erlang doc, which has a lot more details:

If the monitored entity does not exist or it changes monitored state, the caller of monitor/2 is notified by a message on the following format

2 Likes