From b1c915155606da48678c124f2a1bde4a95a9ee61 Mon Sep 17 00:00:00 2001 From: Krzysztof Konopko Date: Thu, 28 Feb 2013 22:33:55 +0000 Subject: [PATCH] _dbus_file_get_contents() - support reading from procfs files For most procfs files (including process status file) fstat() returns size 0. See Notes on stat() manual page [1]. This can be addressed but at least trying to read from a file that looks like an empty one and give up if no data is read. [1] http://man7.org/linux/man-pages/man2/stat.2.html --- dbus/dbus-file-unix.c | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/dbus/dbus-file-unix.c b/dbus/dbus-file-unix.c index 1975933..f82f78b 100644 --- a/dbus/dbus-file-unix.c +++ b/dbus/dbus-file-unix.c @@ -60,6 +60,7 @@ _dbus_file_get_contents (DBusString *str, struct stat sb; int orig_len; int total; + int bytes_read; const char *filename_c; _DBUS_ASSERT_ERROR_IS_CLEAR (error); @@ -104,11 +105,10 @@ _dbus_file_get_contents (DBusString *str, } total = 0; + bytes_read = 0; orig_len = _dbus_string_get_length (str); if (sb.st_size > 0 && S_ISREG (sb.st_mode)) { - int bytes_read; - while (total < (int) sb.st_size) { bytes_read = _dbus_read (fd, str, @@ -145,6 +145,34 @@ _dbus_file_get_contents (DBusString *str, } else { + /* Special file case when fstat() returns 0, e. g. a file in procfs */ + const size_t buffer_size = 512; + + while ((bytes_read = _dbus_read (fd, str, buffer_size))) + { + if (bytes_read < 0) + { + dbus_set_error (error, _dbus_error_from_errno (errno), + "Error reading \"%s\": %s", + filename_c, + _dbus_strerror (errno)); + + _dbus_verbose ("read() failed: %s", + _dbus_strerror (errno)); + + _dbus_close (fd, NULL); + _dbus_string_set_length (str, orig_len); + return FALSE; + } + else + total += bytes_read; + } + + /* OK, it was truly an empty file */ + if (total == 0) + { + _dbus_string_set_length (str, orig_len); + } _dbus_close (fd, NULL); return TRUE; } -- 1.8.1.2