[erlang-questions] Supervising UDP listener

Kamrul Khan dodul@REDACTED
Fri Nov 20 00:45:36 CET 2015


I am trying to make a UDP listener that will be supervised by a supervisor module (Just for learning purpose).  below id my Supervisor code:
-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, {{one_for_one, 5, 60},        [{listener,            {pdmanager, start_link, Port},            permanent, 1000, worker, [pdmanager]}        ]}}.

And my udp listener (pdmanager) looks like the below:
-module(pdmanager).-behaviour(gen_server).
-export([start_link/1]).-export([init/1]).-export([    udplistener/1,    handleudp/1]).
-record(state, {socket}).
start_link(Port) ->    gen_server:start_link({local, pdmanager}, pdmanager, Port, []).
init(Port) ->    io:format("UDP Server starting ~n",[]),    {ok, Socket} = gen_udp:open(Port, [binary, {active, false}]),    spawn_link(pdmanager,udplistener,[Socket]),    {ok, #state{socket=Socket}}.
udplistener(Socket) ->    {ok,Packet} = gen_udp:recv(Socket,0),    {_,_,Msg} = Packet,    if        Msg /= "stop" ->            io:format("Stoping UDP listener ~n", []);        true ->            spawn(pdmanager,handleudp,[Packet]),            udplistener(Socket)    end.    handleudp(Packet) ->    {_,_, Msg} = Packet,    io:format("I have got message : ~s ~n",[Msg]),    {handeling, Packet}.

Now: after compiling I start my program with :
pdmanager:start_link(5678).
It gets started and I can see the "UDP server starting" message in my screen. Next, when I send a message to UDP 5678 port I see the message "stoping UDP listener" as expected.  However, it doesnt restart my server.  I called udplistener/1 function from init/1 using spawn_link. I expected spawn_link will link the new process (udp listener) with the calling process (the worker process in this case) and if udplistener goes down the worker will go down aswell and that will cause the supervisor to restart the worker. However, I didnt work that way. 
How should I do it ? 

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20151120/dc35dc88/attachment.htm>


More information about the erlang-questions mailing list