Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitors in Erlang/OTP

Tags:

erlang

monitor

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().

The output of flush() in my shell is {'DOWN',#Ref<0.0.0.159>,process,<0.69.0>,noproc}

My question is: if process was killed before creating monitor, how come shell got the 'DOWN' message?

like image 325
tintin Avatar asked Dec 11 '14 13:12

tintin


3 Answers

This is a feature which avoids a race condition. Keep in mind that for all the current process knows, the other process might die at any moment. Therefore, it might die just before or just after the call to erlang:monitor, and it would be very cumbersome to have to consider both cases for every monitor.

That's why monitoring a dead process gives a message of the same form as the message you get when a monitored process dies. The only difference is that the exit reason is always given as noproc.

like image 90
legoscia Avatar answered Sep 27 '22 15:09

legoscia


You get a message that say there is noproc. It makes sense since when you start to monitor one process it may have died before. the message is different if you do the reverse:

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> 
like image 40
Pascal Avatar answered Sep 27 '22 16:09

Pascal


If Pid2 terminates with exit reason Reason, a 'DOWN' message is sent to Pid1:

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

If Pid2 does not exist, the 'DOWN' message is sent immediately with Reason set to noproc.

like image 35
BlackMamba Avatar answered Sep 27 '22 17:09

BlackMamba