why
why

Reputation: 24851

How to terminate process with loop function?

I write one module, which has one loop function, the function will send udp packet forever. i debug the program in erlang console, I want to know how to close the UDP socket ? or else erlang will always print the debug message in console. thanks!

start() ->
  {ok, Sock} = gen_udp:open(0, []),
  send(Sock).

send(Sock) ->
  gen_udp:send(Sock, "127.0.0.1", 3211, "hello world"),
  timer:sleep(5000),
  send(Sock). 

Upvotes: 1

Views: 562

Answers (2)

niting112
niting112

Reputation: 2640

There are two things to be considered here

  1. If the process is the owner of the socket.In that case you can directly use gen_udp:close(Sock).
  2. If the process is not the owner of the socket then use gen_udp:controlling_process(Sock,Pid) where Pid is the process id of the new owner of the socket. Now you can use gen_udp:close(Sock) from this process. http://www.erlang.org/doc/man/gen_udp.html

Upvotes: 2

Federico
Federico

Reputation: 5768

To terminate a process you can

exit(Pid,kill).

if you have a receive loop, you can always have a shutdown message that exists the loop.

receive shutdown-> nothing.

Upvotes: 0

Related Questions