[英]Erlang file truncation
I'm trying to write a basic Erlang program that reads in a file in one process and writes the file in another process. 我正在尝试编写一个基本的Erlang程序,该程序在一个进程中读取文件,然后在另一个进程中写入文件。 I'm finding that sometimes the output file gets truncated.
我发现有时输出文件会被截断。
For instance I wrote eunit test. 例如我写了eunit test。 If I run the single test drive_test:write_file_test() the output is correctly written.
如果我运行单个测试drive_test:write_file_test(),则输出将正确写入。 But running drive_test:test() truncates the output file in a different place each time.
但是运行drive_test:test()每次都会在不同的位置截断输出文件。
Do I need to do something special to make sure that the process finishes writing before it closes? 我需要做一些特别的事情来确保进程在关闭之前完成写操作吗?
drive.erl: 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 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 ! 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. 我怀疑这与“ Eunit”的处理方式有关:“ EUnit”可能没有给模块足够的时间在退出并终止所有进程之前
close
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.