How to read environment variable in Glibc code
Mike Frysinger
vapier@gentoo.org
Thu Jan 12 23:26:00 GMT 2012
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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: This is a digitally signed message part.
URL: <http://sourceware.org/pipermail/libc-help/attachments/20120112/ac9fb16d/attachment.sig>
More information about the Libc-help
mailing list