2

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.

4

2 回答 2

7

那么......start/1这里有什么功能?它产生了一个从你开始的进程,loop/1你不仅在你的 shell 中运行它,而且还产生它!因此,您有一个由两个生成的进程组成的链,并且进程在FileServerimiedietly 下死亡,因为它唯一的工作是生成您不知道 pid 的实际文件服务器。

只需更改行:

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

至:

FileServer = afile_server:start(".").

于 2014-12-21T19:39:53.067 回答
5

下图说明了 Lukasz 的解释。

在此处输入图像描述 在此处输入图像描述

于 2014-12-22T09:27:43.203 回答