对于不同的POSIX线程,有没有可能为printf(3)等标准输出实现不同的重定向?标准输入怎么样?每个POSIX线程有不同的标准流
我有很多基于标准输入/输出的代码,我只能将此代码分离到不同的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;
}
真的很好的一点技术上能够解决原来的任务,但在我分析情况更深之后,我更愿意重做代码,因为我打算将来重用它,我不想引入任何看起来像fork()的东西(是的,这超出了原始问题)。 – 2010-05-20 06:42:46