If you really must do this...
First you need to create 2 pthread_key_t
s, one for stdout
and one for stderr
. These can be created using pthread_key_create
, and they must be accessable from all threads. Let's call them stdout_key
and stderr_key
.
When a thread is being created:
FILE *err = ..., *out = ...;
pthread_setspecific(stdout_key, out);
pthread_setspecific(stderr_key, err);
and then in your header file:
#define stdout (FILE*)pthread_getspecific(stdout_key)
#define stderr (FILE*)pthread_getspecific(stderr_key)
#define printf(...) fprintf(stdout, ##__VA_ARGS__)
then just use:
fprintf(stderr, "hello
");
fprintf(stdout, "hello
");
printf("hello
");
I don't recommend this approach though.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…