Erlang文件截断

时间:2009-12-17 15:56:00

标签: erlang

我正在尝试编写一个基本的Erlang程序,该程序在一个进程中读入文件并在另一个进程中写入该文件。我发现有时输出文件会被截断。

例如我写了eunit测试。如果我运行单个测试 drive_test:write_file_test(),则输出正确写入。但运行 drive_test:test()每次都会在不同的位置截断输出文件。

我是否需要做一些特别的事情来确保流程在关闭之前完成写作?

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

截断文件:

$ 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

1 个答案:

答案 0 :(得分:1)

这很可能是与“时间”相关的问题。我怀疑它与“Eunit”如何执行其处理有关:“EUnit”在退出之前可能没有给你的模块close足够的时间,从而终止所有进程。