I'm trying to write a basic Erlang program that reads in a file in one process and writes the file in another process. I'm finding that sometimes the output file gets truncated.
For instance I wrote eunit test. If I run the single test drive_test:write_file_test() the output is correctly written. But running drive_test:test() truncates the output file in a different place each time.
Do I need to do something special to make sure that the process finishes writing before it closes?
drive.erl:
-module(drive).
-include("library.hrl").
-export([init/1]).
init(Drive) ->
loop(Drive).
loop(Drive) ->
receive
{write, Data} ->
write(Drive,Data),
loop(Drive);
close ->
close(Drive)
end.
write(Drive,Data) ->
%io:format("~p", [Data]),
Handler = Drive#drive.volume,
file:write(Handler, [Data]).
close(Drive) ->
Handler = Drive#drive.volume,
file:close(Handler),
io:format("closed ~w~n", [Drive]).
drive_test.erl
-module(drive_test).
-include_lib("eunit/include/eunit.hrl").
-include("library.hrl").
startupShutdown_test() ->
DrivePid = spawn(drive,init,[#drive{number=1}]),
DrivePid ! close.
write_basic_test() ->
{ok, F} =file:open("test/library/eunit.txt", write),
DrivePid = spawn(drive,init,[#drive{number=1,volume=F}]),
DrivePid ! {write, "Some Data"},
DrivePid ! close.
write_file_test() ->
{ok, Fin} = file:open("cathedral.pdf", read),
{ok, Fout} =file:open("test/library/eunit2.txt", write),
DrivePid = spawn(drive,init,[#drive{number=1,volume=Fout}]),
write_file( Fin, DrivePid),
DrivePid !开发者_StackOverflow中文版 close.
write_file(F, DrivePid ) ->
Rd = file:read(F, 256),
case Rd of
{ok, Data} ->
DrivePid ! {write, Data},
write_file(F, DrivePid );
eof -> file:close(F);
_ -> ?_assert(false)
end.
truncated file:
$ ls -l cathedral.pdf test/library/eunit2.txt
-rwx------+ 1 218879 Sep 16 22:21 cathedral.pdf
-rwxr-xr-x 1 60928 Dec 17 09:31 test/library/eunit2.txt
It is most probably a "timing" related problem. I suspect it is related to how "Eunit" performs its processing: "EUnit" probably doesn't give enough time to your module to close
before exiting and thus terminating all processes.
精彩评论