From winstonchang1 at gmail.com  Tue Apr 18 22:20:42 2017
From: winstonchang1 at gmail.com (Winston Chang)
Date: Tue, 18 Apr 2017 15:20:42 -0500
Subject: [Rd] system/system2 and open file descriptors
Message-ID: <CAFOpNVHtSTypK8sXF+XbtDOmyOFQsTrRRasG2-yH5YBnhRVXww@mail.gmail.com>

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]]



[Rd] system/system2 and open file descriptors
Winston Chang