Programming Erlang, 2 e., Chapter 2, Exercise 4, put_file()

David Christensen dpchrist@REDACTED
Fri Dec 31 05:50:38 CET 2021


I am working my way through "Programming Erlang", 2 e.:

2021-12-30 20:00:05 dpchrist@REDACTED ~/sandbox/erlang
$ cat /etc/debian_version ; uname -a ; dpkg-query -W erlang
Linux tinkywinky 4.9.0-17-amd64 #1 SMP Debian 4.9.290-1 (2021-12-12) 
x86_64 GNU/Linux
erlang	1:19.2.1+dfsg-2+deb9u3

Chapter 2, Exercise 4, requests that I add a "put_file" command to the 
file client and server code.  RTFM I found the file:write_file() 
function.  I can test it with the Erlang shell, and it works:

2021-12-30 20:29:34 dpchrist@REDACTED ~/sandbox/erlang
$ erl
Erlang/OTP 19 [erts-8.2.1] [source] [64-bit] [smp:8:8] 
[async-threads:10] [kernel-poll:false]

Eshell V8.2.1  (abort with ^G)
1> file:write_file("foo.2", "this is foo.2\n").
2> halt().

2021-12-30 20:30:09 dpchrist@REDACTED ~/sandbox/erlang
$ cat foo.2
this is foo.2

I have extended afile_server.erl with a "put_file" command that calls 

2021-12-30 20:34:25 dpchrist@REDACTED ~/sandbox/erlang
$ cat ex0204_server.erl
-export([start/1, loop/1]).

start(Dir) -> spawn(afile_server, loop, [Dir]).

loop(Dir) ->
	{Client, list_dir} ->
	    Client ! {self(), file:list_dir(Dir)};
	{Client, {get_file, File}} ->
	    Full = filename:join(Dir, File),
	    Client ! {self(), file:read_file(Full)};
	{Client, {put_file, File, Bytes}} ->
	    Full = filename:join(Dir, File),
	    Client ! {self(), file:write_file(Full, Bytes)}

Testing in the Erlang shell, start() works, the "list_dir" command and 
reply work, and the "get_file" command and reply work, but the shell 
hangs when I attempt to receive a reply for the "put_file" command:

2021-12-30 20:35:23 dpchrist@REDACTED ~/sandbox/erlang
$ erl
Erlang/OTP 19 [erts-8.2.1] [source] [64-bit] [smp:8:8] 
[async-threads:10] [kernel-poll:false]

Eshell V8.2.1  (abort with ^G)
1> c(ex0204_server).
2> Server = ex0204_server:start(".").
3> Server ! {self(), list_dir}.
4> receive A -> A end.
5> Server ! {self(), {get_file, "hello.erl"}}.
6> receive B -> B end.
  {ok,<<"-module(hello).\n-export([start/0]).\n\nstart() ->\n 
io:format(\"hello, world!~n\").\n">>}}
7> Server ! {self(), {put_file, "foo.txt", "foo on you!\n"}}.
{<0.57.0>,{put_file,"foo.txt","foo on you!\n"}}
8> receive C -> C end.

BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
        (v)ersion (k)ill (D)b-tables (d)istribution



More information about the erlang-questions mailing list