From e9bf5aca40f4881fd5f0fa254664467547538688 Mon Sep 17 00:00:00 2001 From: Simon McVittie Date: Thu, 20 Jan 2011 15:54:55 +0000 Subject: [PATCH 2/2] bus-test: close fds beyond 2 on startup If we're going to check for leaks by asserting that we have no open files beyond fd 2, then we ought to make sure that's the case on startup, in case our parent process gave us a fd we didn't want (gdb does this, for instance). --- bus/test-main.c | 2 + dbus/dbus-message-private.h | 2 +- dbus/dbus-message-util.c | 48 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletions(-) diff --git a/bus/test-main.c b/bus/test-main.c index cab7530..7eb9e5e 100644 --- a/bus/test-main.c +++ b/bus/test-main.c @@ -100,6 +100,8 @@ main (int argc, char **argv) return 1; } + _dbus_close_excess_fds (); + _dbus_string_init_const (&test_data_dir, dir); if (!_dbus_threads_init_debug ()) diff --git a/dbus/dbus-message-private.h b/dbus/dbus-message-private.h index 57888fa..7c1f6d5 100644 --- a/dbus/dbus-message-private.h +++ b/dbus/dbus-message-private.h @@ -138,7 +138,7 @@ dbus_bool_t _dbus_message_iter_get_args_valist (DBusMessageIter *iter, int first_arg_type, va_list var_args); - +void _dbus_close_excess_fds(void); void _dbus_check_fdleaks(void); /** @} */ diff --git a/dbus/dbus-message-util.c b/dbus/dbus-message-util.c index f972c8a..29a15c8 100644 --- a/dbus/dbus-message-util.c +++ b/dbus/dbus-message-util.c @@ -138,6 +138,54 @@ check_memleaks (void) } } +/** Initialization for _dbus_check_fdleaks: close any pipes we might have + * open on startup, e.g. gdb leaves our fds 3 and 4 open. + * + * This only needs to work on Linux, because _dbus_check_fdleaks only works + * there too. */ +void +_dbus_close_excess_fds(void) +{ + +#ifdef __linux__ + + DIR *d; + + if ((d = opendir("/proc/self/fd"))) + { + struct dirent *de; + + while ((de = readdir(d))) + { + long l; + char *e = NULL; + int fd; + + if (de->d_name[0] == '.') + continue; + + errno = 0; + l = strtol(de->d_name, &e, 10); + _dbus_assert(errno == 0 && e && !*e); + + fd = (int) l; + + if (fd < 3) + continue; + + if (fd == dirfd(d)) + continue; + + _dbus_close (fd, NULL); + } + + closedir(d); + } +#endif +} + +/** If you're going to call this, you must also call _dbus_close_excess_fds() + * on startup. */ void _dbus_check_fdleaks(void) { -- 1.7.2.3