[Rd] system/system2 and open file descriptors
Winston Chang
winstonchang1 at gmail.com
Tue Apr 18 22:20:42 CEST 2017
It seems that the system() and system2() functions don't close file
descriptors between the fork() and exec() (on Unix platforms, of course).
This means that the child processes inherit open files and socket
connections.
Running this (from a terminal) will result in the child process writing to
a file that was opened by R:
R
f <- file('foo.txt', 'w')
system('echo "abc" >&3')
You can also see the open files if you run the following:
f <- file('foo.txt', 'w')
system2('sleep', '100', wait=F)
And then in another terminal:
lsof -c R -c sleep
it will show that both the R and sleep processes have the file open:
...
R 324 root 3w REG 0,48 0 4259 /foo.txt
...
sleep 327 root 3w REG 0,48 0 4259 /foo.txt
This behavior can cause problems if R spawns a child process that outlives
the R process, but keeps open some resources.
Would it be possible to add an option to close file descriptors for child
processes? It would be nice if that were the default, but I suspect that
making that change would break a lot of existing code.
To take an example from the Python world, subprocess.Popen() has an option,
close_fds, which closes all file descriptors except 0, 1, and 2.
https://docs.python.org/2/library/subprocess.html#popen-constructor
-Winston
[[alternative HTML version deleted]]
More information about the R-devel
mailing list