[go: nahoru, domu]

POSIX: Add code for shuffling file descriptors.

When forking a child process, one often wants to move existing file
descriptors to well known locations (stdout, stderr etc). However,
this is a process bedeviled with corner cases. Consider the case where
you open two file descriptors, get assigned fds 1 and 0 for them and
wish to shuffle them so that they end up in slots 0 and 1. Our current
code fails in this case.

We also have a problem where we're currently trying to mark file
descriptors as close-on-exec rather than closing them in the child
process. This is inherently broken in a multithreaded process where
another thread can open a file descriptor and race the loop which is
trying to mark them.

Thus, on Linux we switch to close-after-fork where we known that no
other threads exist in the process. On Mac, the code is sufficiently
different that this simple fix isn't applicable and one of the Mac
folks will need to take a look.

http://codereview.chromium.org/100127
BUG=11174


git-svn-id: svn://svn.chromium.org/chrome/trunk/src@14978 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/base/process_util.h b/base/process_util.h
index a459ed4..fe1b4d2b4 100644
--- a/base/process_util.h
+++ b/base/process_util.h
@@ -44,6 +44,8 @@
   unsigned long long WriteTransferCount;
   unsigned long long OtherTransferCount;
 };
+
+#include "base/file_descriptor_shuffle.h"
 #endif
 
 #if defined(OS_MACOSX)
@@ -88,7 +90,14 @@
 #if defined(OS_POSIX)
 // Sets all file descriptors to close on exec except for stdin, stdout
 // and stderr.
+// TODO(agl): remove this function
+// WARNING: do not use. It's inherently race-prone in the face of
+// multi-threading.
 void SetAllFDsToCloseOnExec();
+// Close all file descriptors, expect those which are a destination in the
+// given multimap. Only call this function in a child process where you know
+// that there aren't any other threads.
+void CloseSuperfluousFds(const base::InjectiveMultimap& saved_map);
 #endif
 
 #if defined(OS_WIN)