gpt4 book ai didi

c - 每个 POSIX 线程的不同标准流

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:40 24 4
gpt4 key购买 nike

是否有可能为不同的 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;
}

最佳答案

如果您使用 clone 创建线程,您可以做您想做的事,但是 POSIX.1 规定线程必须共享打开的文件描述符。

您可以尝试多种技巧,但实际上您应该将调用转换为接受函数的 FILE * 参数。

关于c - 每个 POSIX 线程的不同标准流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2868145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com