damore
damore

Reputation: 31

Help Understanding Error Report

Can anyone explain why I get the following error when I run: erl -noshell -s simple_server and then telnet 127.0.0.1 1084? The code itself is below the error message.

=ERROR REPORT==== 13-Aug-2011::23:12:05 === Error in process <0.30.0> with exit value: {{badmatch,{error,closed}},[{simple_server,wait_accept,1}]}

  -module(simple_server).
  -compile(export_all).

  start() ->
      {ok, ListenSoc} = gen_tcp:listen(1084, [binary, {active, false}]),
      wait_accept(ListenSoc).

   wait_accept(ListenSoc) ->
      {ok, Socket} = gen_tcp:accept(ListenSoc),
      spawn(?MODULE, wait_accept, [ListenSoc]),
      send_resp(Socket).

  send_resp(Socket) ->
      gen_tcp:send(Socket, "Response from simple server...\n"),
      ok = gen_tcp:close(Socket).

Upvotes: 3

Views: 1196

Answers (2)

hdima
hdima

Reputation: 3637

When a socket is created it's linked to the current process, which known as socket controlling process. When controlling process is terminated all linked sockets are just closed. In your case ListenSoc is closed when send_resp() is over (so controlling process of the socket is terminated) and gen_tcp:accept(ListenSoc) in newly created process returns {error, closed}.

Easiest fix is to add call to gen_tcp:contorolling_process/2 in wait_accept like this:

...
Pid = spawn(?MODULE, wait_accept, [ListenSoc]),
ok = gen_tcp:controlling_process(ListenSoc, Pid),
...

But in real projects it's better to loop in listen socket controlling process. You can get an idea from Nicolas Buduroi answer.

Upvotes: 3

I GIVE CRAP ANSWERS
I GIVE CRAP ANSWERS

Reputation: 18859

This thing:

{{badmatch,{error,closed}},
 [{simple_server,wait_accept,1}]}

should be read as: "We are in simple_server:wait_accept/1" and we got a badmatch error (see http://www.erlang.org/doc/reference_manual/errors.html#id81191). This means that our match expression

{ok, Socket} = gen_tcp:accept(ListenSock),

returned {error, closed} (as it is the only match expression in that function it is simple). Why it returned that is a bit murky to me. The best bet is that the process calling the start/0 function has terminated and then the listen socket has been closed because of that termination (this happens automatically). Note that an error in the erlang shell will restart it and as such close the listen socket.

Upvotes: 4

Related Questions