daemon/shell: refactor redirection of 0/1/2 from /dev/null

Both daemon.c and shell.c contain logic to open FDs 0/1/2 from /dev/null if they are not already open. Move the function in daemon.c to setup.c and use it in shell.c, too. While there, remove a 'not' that inverted the meaning of the comment. The point is indeed to *avoid* messing up. Signed-off-by: Thomas Rast <trast@inf.ethz.ch> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Thomas Rast committed Jul 16, 2013 at 11:27 UTC 1d999ddd1daa6da2779d21b293ea9b275780bff8
4 files changed +17 -21
cache.h
+2
@@ -400,6 +400,8 @@ extern int path_inside_repo(const char *prefix, const char *path);
400 extern int set_git_dir_init(const char *git_dir, const char *real_git_dir, int);
401 extern int init_db(const char *template_dir, unsigned int flags);
402
403 +extern void sanitize_stdfds(void);
404 +
405 #define alloc_nr(x) (((x)+16)*3/2)
406
407 /*
daemon.c
-12
@@ -1047,18 +1047,6 @@ static int service_loop(struct socketlist *socklist)
1047 }
1048 }
1049
1050 -/* if any standard file descriptor is missing open it to /dev/null */
1051 -static void sanitize_stdfds(void)
1052 -{
1053 - int fd = open("/dev/null", O_RDWR, 0);
1054 - while (fd != -1 && fd < 2)
1055 - fd = dup(fd);
1056 - if (fd == -1)
1057 - die_errno("open /dev/null or dup failed");
1058 - if (fd > 2)
1059 - close(fd);
1060 -}
1061 -
1050 #ifdef NO_POSIX_GOODIES
1051
1052 struct credentials;
setup.c
+12
@@ -872,3 +872,15 @@ const char *resolve_gitdir(const char *suspect)
872 return suspect;
873 return read_gitfile(suspect);
874 }
875 +
876 +/* if any standard file descriptor is missing open it to /dev/null */
877 +void sanitize_stdfds(void)
878 +{
879 + int fd = open("/dev/null", O_RDWR, 0);
880 + while (fd != -1 && fd < 2)
881 + fd = dup(fd);
882 + if (fd == -1)
883 + die_errno("open /dev/null or dup failed");
884 + if (fd > 2)
885 + close(fd);
886 +}
shell.c
+3 -9
@@ -134,7 +134,6 @@ int main(int argc, char **argv)
134 char *prog;
135 const char **user_argv;
136 struct commands *cmd;
137 - int devnull_fd;
137 int count;
138
139 git_setup_gettext();
@@ -143,15 +142,10 @@ int main(int argc, char **argv)
142
143 /*
144 * Always open file descriptors 0/1/2 to avoid clobbering files
146 - * in die(). It also avoids not messing up when the pipes are
147 - * dup'ed onto stdin/stdout/stderr in the child processes we spawn.
145 + * in die(). It also avoids messing up when the pipes are dup'ed
146 + * onto stdin/stdout/stderr in the child processes we spawn.
147 */
149 - devnull_fd = open("/dev/null", O_RDWR);
150 - while (devnull_fd >= 0 && devnull_fd <= 2)
151 - devnull_fd = dup(devnull_fd);
152 - if (devnull_fd == -1)
153 - die_errno("opening /dev/null failed");
154 - close (devnull_fd);
148 + sanitize_stdfds();
149
150 /*
151 * Special hack to pretend to be a CVS server