Monitors in erlang

I am new to Erlang and programming. I have a question about monitors.

1> Pid=spawn(fun() -> timer:sleep(500000) end).
2> exit(Pid, kill).
3> Ref=erlang:monitor(process, Pid).

4> flush().

output flush () Shell received {'DOWN', # Ref <0.0.0.159>, process, <0,69.0>, noproc}

My question is: if the process was killed before the monitor was created, how did it happen that the shell received the "DOWN" message?

+4
source share
3 answers

This is a function that avoids the race condition. Keep in mind that for what the current process knows, another process may die at any time. Therefore, he may die immediately or immediately after the call erlang:monitor, and it would be very cumbersome to consider both cases for each monitor.

, , , , . , noproc.

+6

, noproc. , , , , . , :

1> Pid=spawn(fun() -> timer:sleep(500000) end).
<0.35.0>
2> exit(Pid, kill).
true
3> Ref=erlang:monitor(process, Pid).
#Ref<0.0.0.38>
4> flush().
Shell got {'DOWN',#Ref<0.0.0.38>,process,<0.35.0>,noproc}
ok
5> 
5> Pid1=spawn(fun() -> timer:sleep(500000) end).
<0.40.0>
6> Ref1=erlang:monitor(process, Pid1).          
#Ref<0.0.0.53>
7> exit(Pid1, kill).                            
true
8> flush().                                     
Shell got {'DOWN',#Ref<0.0.0.53>,process,<0.40.0>,killed}
ok
9> 
+1

If Pid2 terminates with the cause reason “Cause”, a “DOWN” message is sent to Pid1:

{'DOWN', Ref, process, Pid2, Reason}

If Pid2 does not exist, a “DOWN” message is sent immediately with the reason set to noproc.

0
source

All Articles