Search code examples
concurrencyerlangerlang-shell

File Server erlang response


I am trying to follow the very first example given in the Programming Erlang, Software for a concurrent world by Joe Armstrong. Here is the code:

-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)};
        {Client, {get_file, File}} ->
            Full = filename:join(Dir,File),
            Client ! {self(), file:read_file(Full)}
    end,
    loop(Dir).

Then I run this in the shell:

c(afile_server).
FileServer = spawn(afile_server, start, ".").
FileServer ! {self(), list_dir}.
receive X -> X end.

In the book a list of the files is returned as expected however in my shell it looks as if the program has frozen. Nothing gets returned yet the program is still running. I'm not familiar at all with erlang however I can understand how this should work.

I'm running this in Windows 7 64-bit. The directory is not empty as it contains a bunch of other erlang files.


Solution

  • So... what start/1 function is doing here? It's spawning a process which starts from loop/1 and you don't just run it in your shell but spawning it too! So you have a chain of two spawned processes and process under FileServer dies imiedietly because its only job is to spawn actual file server which pid is unknown to you.

    Just change line:

    FileServer = spawn(afile_server, start, ".").

    to:

    FileServer = afile_server:start(".").