I am learning Erlang. I want to make a UDP Listener that will be supervised by a supervisor. So if the listener process goes down supervisor will restart the process. Initially I just made a simple UDP listener which works as expected.
startudplistener() ->
{ok, Socket} = gen_udp:open(9000,[binary,{active,false}]),
Pid = spawn(pdmanager,udplistener,[Socket]),
{ok, Pid}.
udplistener(Socket) ->
{ok,Packet} = gen_udp:recv(Socket,0),
spawn(pdmanager,handleudp,[Packet]),
udplistener(Socket).
handleudp(Packet) ->
{_,_, Msg} = Packet,
io:format("I have got message : ~s ~n",[Msg]),
{handeling, Packet}.
So, what I want to do is to monitor the udplistener process. For this first I modified my module to a gen_server one. Write a supervisor module afterwards. My supervisor looks like this:
-module(pdmanager_sup).
-behaviour(supervisor).
-export([start_link/1]).
-export([init/1]).
start_link(Port) ->
supervisor:start_link({local,?MODULE}, ?MODULE, Port).
init(Port) ->
{ok, Socket} = gen_udp:open(Port, [binary, {active, false}]),
{ok, {{one_for_one, 5, 60},
[{listener,
{pdmanager, start_link, [Socket]},
permanent, 1000, worker, [pdmanager]}
]}}.
So what Im trying to so is to, open up a new udp socket and pass it to my server and the server will keep on listening to the socket while the supervisor will monitor it. So I came up with the following code.
start_link(Socket) ->
gen_server:start_link({local, pdmanager}, pdmanager, Socket, []).
init(Socket) ->
io:format("UDP Server starting ~n",[]),
spawn_link(pdmanager,udplistener,[Socket]),
{ok, #state{socket=Socket}}.
I am a bit confused with spawn_link that I added within my init function. spawn_link is opening up another process, however it is making a link with the calling process. As per my understanding my supervisor will monitor the calling process here. So, how would my supervisor behave incase my udplistener goes down? If it doesn't work the way I am expecting (im expecting it will restart my server) what is the best way to do it?