如何在Erlang中刷新io缓冲区?

f45qwnt8  于 2022-12-08  发布在  Erlang
关注(0)|答案(3)|浏览(159)

How do you flush the io buffer in Erlang?
For instance:

> io:format("hello"),
> io:format(user, "hello").

This post seems to indicate that there is no clean solution.
Is there a better solution than in that post?

ggazkfy8

ggazkfy81#

可悲的是,除了在io/内核子系统中正确地实现一个flush“命令”* 和 * 确保实现实际io的低级驱动程序支持这样一个命令之外,你真的必须在关闭之前简单地依赖系统停顿。我认为这是一个失败。
请查看stdlib中的io.erl/io_lib.erl和内核中的file_io_server.erl/prim_file.erl,以了解详细信息。
例如,在file_io_server(它有效地从io/io_lib获取请求并将其路由到正确的驱动程序)中,命令类型为:

{put_chars,Chars}
{get_until,...}
{get_chars,...}
{get_line,...}
{setopts, ...}

(i.e.不冲水)!
当然,作为一种替代方法,你可以在每次写操作后总是关闭输出(这将强制刷新)。我的一个日志模块每次都执行类似的操作,而且它看起来并不那么慢(它是一个gen_server,通过cast消息接收日志):

case file:open(LogFile, [append]) of
    {ok, IODevice} ->
    io:fwrite(IODevice, "~n~2..0B ~2..0B ~4..0B, ~2..0B:~2..0B:~2..0B: ~-8s : ~-20s : ~12w : ",
          [Day, Month, Year, Hour, Minute, Second, Priority, Module, Pid]),
    io:fwrite(IODevice, Msg, Params),
    io:fwrite(IODevice, "~c", [13]),
    file:close(IODevice);
q9rjltbz

q9rjltbz2#

io:put_chars(<<>>)

在剧本的最后一句对我很管用。

b4lqfgs4

b4lqfgs43#

你可以跑

flush().

或尝试

flush()->
receive
    _ -> flush()
after 0 -> ok
end.

这跟同花C差不多。

相关问题