Lethi
Lethi

Reputation: 1177

Monitors vs Supervisors?

Is supervisors same as monitor? Is good to use monitor or would be better to use supervisor?

I unsure when to use monitor instead of supervisor.

Upvotes: 2

Views: 1399

Answers (2)

Pascal
Pascal

Reputation: 14042

A supervisor is an OTP behavior. You will use this in a hierarchy of processes, on top of the hierarchy are the supervisors whose responsibility is to apply the restart strategy you have defined for each child.

a child will be another supervisor, or a worker.

the workers are the modules that do the job. In an OTP architecture they usually are gen_server, gen_event, gen_fsm... They may terminate normally (in this case nothing is done) or crash. The supervisor will then apply the restart strategy:

  • one_for_one: restart the process
  • one_for_all: terminate all children and restart them all
  • rest_for_one: terminate the following children in the start list and restart them in the right order

To achieve this, the supervisors use a bi-directional connection created by the link or spawn_link functions. The 2 processes are linked; that means that if any of them crashes, the other one will crash also, unless it set process_flag(trap_exit, true) and in this case it will receive the message {'EXIT',FromPid,Reason}

here is an example of such a hierarchy with 3 supervisors (in my case Task_Sup use a simple_one_for_one strategy, and the children are created using Create(Task) from Mngr_Server, the same Mngr_server monitors each children):

enter image description here

a Monitor is a unidirectional connection between 2 processes created by calling

Ref = erlang:monitor(process, Pid2) in a process Pid1. then if Pid2 terminates, Pid1 will receive a message

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

Pid1 must check for incoming message to get informed of Pid2 termination.

Upvotes: 1

macintux
macintux

Reputation: 894

Suggested reading: http://learnyousomeerlang.com/errors-and-processes#monitors

A supervisor is a very special relationship. To anthropomorphize, as a supervisor I am directly responsible for the well-being of a subordinate. If he/she fails, I am required to do something to fix the situation.

Links are used by supervisors and other directly related processes that are all part of the same system.

Monitors, to my admittedly untutored eyes, are similar to links but primarily useful for external processes that have an interest in whether a process is running, but aren't directly related.

To use DNS as an example, it would be helpful to know whether a DNS server is running before I waste time trying to get a response from it, but if the DNS server goes down, it's not my job to start it back up. I just need to switch to a different DNS server.

Upvotes: 7

Related Questions