# HG changeset patch # User Mathias De Mare # Date 2020-11-02 10:58:34 # Node ID 8711dc13474ce3d6db8c21389a994867331e348d # Parent 91c41ea14598cf56d6cb1a160a18a7dbe7a47ae0 chg: close file descriptors when starting the daemon 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). Differential Revision: https://phab.mercurial-scm.org/D9268 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 +#include #include #include #include @@ -269,6 +270,31 @@ static void execcmdserver(const struct c } } + /* 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)