【问题标题】:Erlang file truncationErlang 文件截断
【发布时间】:2010-12-27 17:19:11
【问题描述】:

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

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

我需要做一些特别的事情来确保进程在关闭之前完成写入吗?

驱动器.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

【问题讨论】:

    标签: erlang


    【解决方案1】:

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

    【讨论】:

    • 谢谢,我认为已经解决了。我更改了所有的 eunit 文本,因此直到他们从驱动进程收到关闭消息后才完成。
    猜你喜欢
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2010-10-09
    • 2016-01-10
    相关资源
    最近更新 更多