From: Denys Vlasenko Date: Tue, 24 Jan 2012 09:17:18 +0000 (+0100) Subject: Use single fprintf in verror_msg() X-Git-Tag: v4.7~201 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=82bb78c149a1b527f4ae7a764be29a9c85067b29;p=strace 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 --- 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, ...)