Communication process execution

I just started reading the Erlang Programming book. There is a very one example that only works with a file.

If I do:

> c(afile_server).
> c(afile_client).
> Server = afile_server:start(".").
> client:get_file(Server, "file1").
> client:get_file(Server, "file2").
> client:get_file(Server, "file3").

Everything works only with the file. The contents of the three files are displayed.

But if I do this:

> c(afile_server).
> Server = afile_server:start(".").
> Server ! { self(), { get_file, "file1" } }.
> receive 
   { Server, Content }
      Content
  end.

It only works with a file. But if I change the file I'm trying to read (after the call for the first time), for example.

> Server ! { self(), { get_file, "file2" } }.
> receive 
   { Server, Content }
      Content
  end.

Receive blocks and do not return anything. Could you guys help? I think this is a very stupid mistake! Regards.

Files:

Server:

-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).

Client

%% ---
%%  Excerpted from "Programming Erlang, Second Edition",
%%  published by The Pragmatic Bookshelf.
%%  Copyrights apply to this code. It may not be used to create training material, 
%%  courses, books, articles, and the like. Contact us if you are in doubt.
%%  We make no guarantees that this code is fit for any purpose. 
%%  Visit http://www.pragmaticprogrammer.com/titles/jaerlang2 for more book information.
%%---
-module(afile_client).
-export([ls/1, get_file/2]).

ls(Server) ->
    Server ! {self(), list_dir},
    receive 
    {Server, FileList} ->
        FileList
    end.

get_file(Server, File) ->
    Server ! {self(), {get_file, File}},
    receive 
    {Server, Content} ->
        Content
    end.
+3
source share
1 answer

, Content receive, , , , receive , . , Content "" f(Content).

1> c(afile_server).
{ok,afile_server}
2> Server = afile_server:start(".").
<0.64.0>
3> Server ! { self(), { get_file, "file1" } }.
{<0.57.0>,{get_file,"file1"}}
4> receive {Server, Content} -> Content end.
{ok,<<"file1\n">>}
5> Server ! { self(), { get_file, "file2" } }.
{<0.57.0>,{get_file,"file2"}}
6> receive {Server, Content} -> Content after 1000 -> timeout end.
timeout
7> receive {Server, Content2} -> Content2 end.
{ok,<<"file2\n">>}
8> Server ! { self(), { get_file, "file3" } }.
{<0.57.0>,{get_file,"file3"}}
9> receive {Server, Content} -> Content after 1000 -> timeout end.
timeout
10> f(Content).
ok
11> receive {Server, Content} -> Content after 1000 -> timeout end.
{ok,<<"file3\n">>}
+3

Source: https://habr.com/ru/post/1656165/


All Articles