I have two tasks:
Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, restart it
Here is the code that I built:
proc() ->
receive
p -> exit("I need to die")
end.
start_and_monitor(0) ->
spawn_monitor(proc()),
receive
{'DOWN',_,process,_,_} -> spawn_monitor(proc())
end;
start_and_monitor(Int) ->
spawn_monitor(proc()),
start_and_monitor(Int - 1).
Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, kill all the worker processes and restart them all.
Here I thought that instead of monitoring all of the process I could link all the small processes and monitor a major process that is linked to all of them. Here is the code:
start_and_monitor_but_kill(Int) ->
{Pid,Ref} = spawn_monitor(start_monitor_kill(Int)),
receive
{'DOWN', Ref, process, _, _} -> start_and_monitor_but_kill(Int)
end.
start_monitor_kill(0) ->
spawn_link(proc());
start_monitor_kill(Int) ->
spawn_link(proc()),
start_monitor_kill(Int-1).
Is there any way that I can improve my code? Am I using all the erlang primitives correctly ? Any criticism is highly appreciated.
Also I am very curious if I used the primitives correctly. For example I used the monitor process without giving a ref. Is this acceptable in this case?
spawn_link/1
, andspawn_monitor/1
at erlang doc – Pascal Mar 10 at 12:12