[erlang-questions] Problems with prim_file and ports

Alex Shturm alex.shturm@REDACTED
Wed Sep 10 08:18:09 CEST 2014


Hello everybody.

I'm having a problem with the way prim_file deals with ports; hope you can
suggest something.

I have a gen_server that handles requests to read files. The volume of
requests is quite high, so I try to optimize everything I can. In
particular, in the beginning I open a port by calling prim_file:open/1, and
then use this port for all subsequent file operations.

I found that calling prim_file:read_file/2 (to read the entire file) causes
no problems.
However calling prim_file:open/3 + prim_file:read/2 + prim_file:close/1 (in
order to read a portion of a file) causes the port to close.

This can be reproduced like this:

Eshell V5.10.4  (abort with ^G)
1>
1> Filename = "/tmp/testfile".
"/tmp/testfile"
2> os:cmd("touch /tmp/testfile").
[]
3> {ok, Port} = prim_file:open([binary]).
{ok,#Port<0.611>}
4> prim_file:read_file(Port, Filename).
{ok,<<>>}
5> prim_file:read_file(Port, Filename).
{ok,<<>>}
6> {ok, Fd} = prim_file:open(Port, Filename, [read, binary]).
{ok,{file_descriptor,prim_file,{#Port<0.611>,11}}}
7> prim_file:read(Fd, 100).
eof
8> prim_file:close(Fd).
ok
9> prim_file:read_file(Port, Filename).
{error,einval}
10>

The reason for this behavior is prim_file:close/1 which in addition to
issuing a driver command "file close" also closes the port.

This looks counterintuitive to me: prim_file:open/3 did not open the port,
so why prim_file:close/1 should close it?

Can somebody provide some insight into this issue, and/or a workaround?

Thank you,
Alex
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140909/7213bbff/attachment.htm>


More information about the erlang-questions mailing list