Disable auto-close of a file descriptor when opened with `file:open`

We are trying to open a file in the init_per_suite using the file:open function, but when we try to write bytes in the file from a test we got an error saying that the IoDevice is closed.
This happens because of:
" IoDevice is really the pid of the process that handles the file. This process monitors the process that originally opened the file (the owner process). If the owner process terminates, the file is closed and the process itself terminates too. An IoDevice returned from this call can be used as an argument to the I/O functions (see io(3) )."

Is there a way to avoid this behaviour and control programmatically the close of the file?

1 Like

init_per_suite is executed in a separate process. So if you want to open a file in init_per_suite and close in end_per_suite, you can do something like this:

init_per_suite(Config) ->
    Self = self(),
    FileProc = spawn(fun() ->
        {ok, Fd} = file:open("myfile"),
        Self ! {fd, Fd},
        receive after infinity -> ok end
        {fd, Fd} ->
            [{proc, FileProc}, {fd, Fd} | Config]

end_per_suite(Config) ->
    FileProc = proplists:get_value(proc, Config),
    exit(FileProc, kill).

Thanks max-au for the idea. For now we have decided to use the ct:log facility

1 Like

Open the file from init_per_testcase, that runs in the same process as the test itself.

1 Like