Is there any possibility to achieve different redirections for standard output like printf(3) for different POSIX thread? What about standard input?
I have lot of code based on standard input/output and I only can separate this code into different POSIX thread, not process. Linux operation system, C standard library.
I know I can refactor code to replace printf() to fprintf() and further in this style.
But in this case I need to provide some kind of context which old code doesn’t have.
So doesn’t anybody have better idea (look into code below)?
#include <pthread.h>
#include <stdio.h>
void* different_thread(void*)
{
// Something to redirect standard output which doesn't affect main thread.
// ...
// printf() shall go to different stream.
printf("subthread test\n");
return NULL;
}
int main()
{
pthread_t id;
pthread_create(&id, NULL, different_thread, NULL);
// In main thread things should be printed normally...
printf("main thread test\n");
pthread_join(id, NULL);
return 0;
}
You can do what you want if you create threads using
clone, but POSIX.1 says that the threads must share open file discriptors.There are several tricks you could try, but you really should just convert the calls to the
FILE *argument accepting functions.