D9268: chg: close file descriptors when starting the daemon

Mathiasdm (Mathias De Maré) phabricator at mercurial-scm.org
Mon Nov 2 13:20:56 UTC 2020


Mathiasdm created this revision.
Herald added a reviewer: hg-reviewers.
Herald added a subscriber: mercurial-patches.

REVISION SUMMARY
  It's good practice to close file descriptors when forking to start a daemon.
  This did not appear to happen yet, which results in flock hanging
  in one location in our system (because the chg daemon keeps
  the locked file open).

REPOSITORY
  rHG Mercurial

BRANCH
  stable

REVISION DETAIL
  https://phab.mercurial-scm.org/D9268

AFFECTED FILES
  contrib/chg/chg.c

CHANGE DETAILS

diff --git a/contrib/chg/chg.c b/contrib/chg/chg.c
--- a/contrib/chg/chg.c
+++ b/contrib/chg/chg.c
@@ -8,6 +8,7 @@
  */
 
 #include <assert.h>
+#include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <signal.h>
@@ -269,6 +270,31 @@
 		}
 	}
 
+	/* close any open files to avoid hanging locks */
+	DIR *dp = opendir("/proc/self/fd");
+	if (dp != NULL) {
+		debugmsg("closing files based on /proc contents");
+		struct dirent *de;
+		while ((de = readdir(dp))) {
+			char *end;
+			long fd_value = strtol(de->d_name, &end, 10);
+			if (end == de->d_name) {
+				/* unable to convert to int (. or ..) */
+				continue;
+			}
+			if (errno == ERANGE) {
+				debugmsg("tried to parse %s, but range error occurred", de->d_name);
+				continue;
+			}
+			if (fd_value > STDERR_FILENO) {
+				int res = close(fd_value);
+				if (res) {
+					debugmsg("tried to close fd %ld: %d (errno: %d)", fd_value, res, errno);
+				}
+			}
+		}
+	}
+
 	if (putenv("CHGINTERNALMARK=") != 0)
 		abortmsgerrno("failed to putenv");
 	if (execvp(hgcmd, (char **)argv) < 0)



To: Mathiasdm, #hg-reviewers
Cc: mercurial-patches, mercurial-devel


More information about the Mercurial-devel mailing list