[erlang-questions] Should I use file:close/1 in terminate/2?

Sergey Samokhin prikrutil@REDACTED
Fri May 22 00:03:14 CEST 2009


Hello.

I have often wanted to ask if it's safe to let the file opened in
init/1 of gen_server/gen_fsm be closed automatically when a server
terminates?

I have been using this kind of code so far:

% --------------
-behaviour(gen_server).

init(File) ->
    process_flag(trap_exit, true), % to guarantee that the terminate/2
will be called by supervisor
    file:open(File, [append]).

<...>

terminate(_Reason, Fd) ->
    file:close(Fd). % <- Should I do it?
% --------------

As you have seen, I had to turn my process into system one, to be able
to close my file directly by close/1. Sometimes it's necessary to
close a file by hand (e.g. when you are deleting your handler from
gen_event manager, which doesn't create brand new process per each
handler), but sometimes it can be a bit awkwardly to trap all the
exits for that to work.

Could you take a look at the following example and say whether Fd is
closed in a consistent manner as if I used file:close/1 or not?

% --------------
-behaviour(gen_server).

init(File) ->
    file:open(File, [append]).

<...>

terminate(_Reason, Fd) ->
    ok.
% --------------

Thanks.

-- 
Sergey Samokhin



More information about the erlang-questions mailing list