This is the mail archive of the libc-help@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: How to read environment variable in Glibc code


On Monday 09 January 2012 23:39:22 naveen yadav wrote:
>  Thanks a lot for your valuable input. I want to control printf from
> environment variable.
>  If I set Environment variable 1 it enable print to screen if i put
> Environment variable to 0 it disable to screen.
> 
> Actual I have already prebuild software, I want to control its o/p
> using glibc and Environment variable.

libfoo.c:
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

static FILE *null_fp;

int printf(const char *format, ...)
{
        const char *var = getenv("MY_VAR");
        va_list ap;
        int ret;
        FILE *out;

        if (!null_fp) {
                null_fp = fopen("/dev/null", "w");
                assert(null_fp);
        }

        if (!var || atoi(var) != 1)
                out = null_fp;
        else
                out = stdout;

        va_start(ap, format);
        ret = vfprintf(out, format, ap);
        va_end(ap);

        return ret;
}

test.c:
#include <stdio.h>
main(int argc){printf("HI %i\n", argc);}

$ gcc test.c -o test
$ gcc -fPIC -shared libfoo.c -o libfoo.so
$ MY_VAR=0 LD_PRELOAD=./libfoo.so ./test
$ MY_VAR=1 LD_PRELOAD=./libfoo.so ./test
HI 1

however, your effort is likely doomed to fail as there are many ways people can 
write to stdout.  off the top of my head:
	- vprintf(...)
	- vfprintf(stdout, ...)
	- fprintf(stdout, ...)
	- vfprintf(stdout, ...)
	- puts(...)
	- putchar(...)
	- fputs(..., stdout)
	- fputc(..., stdout)
	- putc(..., stdout)
	- fwrite(..., stdout)
	- write(1, ...)

and you're likely to hit this implicitly -- gcc/glibc optimize printf("FOO") 
into puts("FOO") automatically
-mike

Attachment: signature.asc
Description: This is a digitally signed message part.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]