是否有可能为不同的 POSIX 线程实现不同的标准输出重定向,如 printf(3)?标准输入呢?
我有很多基于标准输入/输出的代码,我只能将这些代码分成不同的 POSIX 线程,而不是进程。Linux操作系统,C标准库。我知道我可以重构代码以将 printf() 替换为 fprintf() 并进一步采用这种风格。但在这种情况下,我需要提供某种旧代码所没有的上下文。
那么没有人有更好的主意(查看下面的代码)吗?
#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;
}