What happens when link and monitor the same process in Erlang

If process A link to B and A monitor B, when B dies, what happens to A? will A receive two messages? one is monitor ‘Down’ message and the other is exit message from B, if it is, what will A do?

1 Like

It should depend on if A traps exits. If not, then it will exit when B dies – likely receiving no message in advance. If it does then the exit of B will be converted into an exit message delivered to A and A will also be notified by the monitor that B died.

2 Likes

what is the order of these two messages? the exit message for link and the ‘Down’ message for monitor

1 Like

I have no idea and tbh I probably wouldn’t depend on the order anyways.

4 Likes

Got the answer from here, thank you

1 Like

As this is not documented anywhere (the author of the post answering your question in the linked StackOverflow thread had to look into the emulator code), it is not to be relied upon. If something is not explicitly documented one way or another, it may change without notice, even from one minor version to another.

2 Likes

You can try it by a small erlang code

I tried it, when B exit, A will receive two messages, an exit message and a monitor ‘Down’ message, but the order is not always the same

That means you can’t doing any expectations about this behaviour, but this situation will never happen in real applications :
1- If the process can trap exists, then it should not monitor the linked one
2- If it can’t trap exists, then it will receive just Down message when it monitor the other process, it can’t receive EXIT message

Why just can receive the ‘Down’ message? if it’s possible that receive EXIT message first and then the process exit without receive the ’

Down

’ message?

No I mean that it will not receive {'EXIT',....}as a message, but as a killer signal which have priority than all precedent queue’s messages and which will shutdown immediately the process

Got it, but in my tests, sometimes the monitor message will arrive earlier

Yeah as I said you can’t expect, the exit signal is prioritary than all queue’s messages but here Down message is received(empty queue) before the exit signal is generated, maybe next time the exit will be generated first…so you can’t expect

Ok, thank you very much!

Any problem you’re welcome :slightly_smiling_face:

https://www.erlang.org/doc/reference_manual/processes.html#receiving_exit_signals

1 Like