From 82bb78c149a1b527f4ae7a764be29a9c85067b29 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Tue, 24 Jan 2012 10:17:18 +0100 Subject: [PATCH] Use single fprintf in verror_msg() This change partially reverts commit 44d0532. In code before commit 44d0532, single fprintf was used on purpose: we want to send entire message as one write() call. Since stderr is unbuffered, separate fprintf's to it always result in separate writes, they are not coalesced. If we aren't the only program which writes to this particular stderr, this may result in interleaved messages. Since this function is not performance critical, I guess it's ok to make it less efficient. * strace.c (verror_msg): Attempt to print the message in single write operation. Use separate fprintfs as a fallback if malloc fails. Signed-off-by: Denys Vlasenko --- strace.c | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/strace.c b/strace.c index f1f634ba..64e90e71 100644 --- a/strace.c +++ b/strace.c @@ -222,14 +222,34 @@ static void die(void) static void verror_msg(int err_no, const char *fmt, va_list p) { + char *msg; + fflush(NULL); - fprintf(stderr, "%s: ", progname); - vfprintf(stderr, fmt, p); - if (err_no) - fprintf(stderr, ": %s\n", strerror(err_no)); - else - putc('\n', stderr); - fflush(stderr); + + /* We want to print entire message with single fprintf to ensure + * message integrity if stderr is shared with other programs. + * Thus we use vasprintf + single fprintf. + */ + msg = NULL; + vasprintf(&msg, fmt, p); + if (msg) { + if (err_no) + fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no)); + else + fprintf(stderr, "%s: %s\n", progname, msg); + free(msg); + } else { + /* malloc in vasprintf failed, try it without malloc */ + fprintf(stderr, "%s: ", progname); + vfprintf(stderr, fmt, p); + if (err_no) + fprintf(stderr, ": %s\n", strerror(err_no)); + else + putc('\n', stderr); + } + /* We don't switch stderr to buffered, thus fprintf(stderr) + * always flushes its output and this is not necessary: */ + /* fflush(stderr); */ } void error_msg(const char *fmt, ...) -- 2.40.0