[erlang-questions] Server stops responding

Steve Vinoski <>
Fri May 1 23:35:55 CEST 2015


On Fri, May 1, 2015 at 3:54 PM, Sid Muller <> wrote:

> Hi,
>
> Can someone explain why the code from afile_server responds only once. If
> I send the Pid a different message it just hangs the shell.
>
> Here is the code below:
> -module(afile_server).
> -export([start/1, loop/1]).
> start(Dir) -> spawn(afile_server, loop, [Dir]).
> loop(Dir) ->
>     receive
>         {Client, list_dir} ->
>             Client ! {self(), file:list_dir(Dir)},
>             loop(Dir);
>         {Client, {get_file, File}} ->
>             Full = filename:join(Dir, File),
>             Client ! {self(), file:read_file(Full)},
>             loop(Dir)
>     end,
>     loop(Dir).
>
> We compile it and run it:
> 1> c(afile_server).
> {ok,afile_server}
> 2> Pid = afile_server:start(".").
> <0.40.0>
>
> We send it a list_dir message:
> <pre><code>
> 3> Pid ! {self(), list_dir}.
> {<0.33.0>,list_dir}
>
> And receive reponse just fine:
> 4> receive X -> X end.
> {<0.40.0>,
>  {ok,["afile_server.erl", "afile_server.beam"]}}
>

You've just received X...


> Send the same message again:
> 5> Pid ! {self(), list_dir}.
> {<0.33.0>,list_dir}
>
> And receive response, no problem:
> 6> receive X -> X end.
> {<0.40.0>,
>  {ok,["afile_server.erl", "afile_server.beam"]}}
>


...and now you've received the same X...


> Now we send a get_file message:
> 7> Pid ! {self(), {get_file, "afile_server.erl"}}.
> {<0.33.0>,{get_file,"afile_server.erl"}}
>
> But receive hangs:
> 8> receive X -> X end.
>

...and now you're trying to receive X, which is already bound to the
previous message, but that's not the message you're getting. If you were to
use some variable name other than X, a variable that's not yet bound, it
would work fine.

--steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150501/c42e2f5c/attachment.html>


More information about the erlang-questions mailing list