Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I temporarily redirect printf output to a c-string?

I'm writing an assignment which involves adding some functionality to PostgreSQL on a Solaris box. As part of the assignment, we need to print some information on the client side (i.e.: using elog.)

PostgreSQL already has lots of helper methods which print out the required information, however, the helper methods are packed with hundreds of printf calls, and the elog method only works with c-style strings.

Is there I way that I could temporarily redirect printf calls to a buffer so I could easily send it over elog to the client?

If that's not possible, what would be the simplest way to modify the helper methods to end up with a buffer as output?

like image 630
Ben S Avatar asked Dec 02 '25 10:12

Ben S


1 Answers

If you define your own version of printf and link to it prior to the libc version, your version will supersede the standard version.

You should also be able to supersede the standard version by using LD_PRELOAD to load a library that has printf defined.

To write your own printf, you will want to use stdarg functionality:

int printf(const char *fmt, ...)
{
    int rv;
    va_list ap;
    va_start(ap, fmt);

    if (redirect_printf)
    {
#ifdef HAVE_VLOG
        // If you have a vlog function that takes a va_list
        vlog(fmt, ap);
        rv = ...;
#else
        char buffer[LARGESIZE];
        rv = vsnprintf(buffer, sizeof(buffer), fmt, ap);

        log(buffer);
#endif;
    }
    else
    {
        rv = vprintf(fmt, ap);
    }

    return rv;
}

This simple version will truncate data when the final formatted output is greater than LARGESIZE. If you don't want that, you can also call vsnprintf first with a NULL buffer to get the final size, do a dynamic allocation and then a second call to vsprintf to format the buffer.

like image 128
R Samuel Klatchko Avatar answered Dec 05 '25 01:12

R Samuel Klatchko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!