我使用 win8 Consumer preview build 8250 执行程序,在 win7 上运行正常 该程序使用以下宏/函数:
#if defined(_WIN32)
#include <io.h>
#define streamDup(fd1) _dup(fd1)
#define streamDup2(fd1,fd2) _dup2(fd1,fd2)
#endif
static int acquireOutputStream()
{ int fd = streamDup(fileno(stdout));
FILE* f = freopen("tmp","w",stdout);
return fd; }
static void releaseOutputStream(int fd)
{ fflush(stdout);
streamDup2(fd,fileno(stdout));
close(fd);
}
程序执行以下操作:
for (int i = 0; i < 1000;++i) {
int fd = acquireOutputStream();
printf("redirect %d\n",i);
releaseOutputStream(fd);
printf("test %d\n",i);
}
每次我运行它时,它都会打印到文件 tmp 随机数的正确“重定向 j”打印: 在它之后,文件对于剩余的执行是空的。(f 指针在 acquireOutputStream 中永远不会为 NULL)“test j”总是被正确打印。 可能是什么问题?这是 win 8 上的已知问题吗?
最佳答案
我发现您的代码存在一个小问题。
static void releaseOutputStream(int fd)
{ fflush(stdout);
streamDup2(fd,fileno(stdout));
close(fd);
}
在此函数中,您不会在 dup2 调用 (fclose(stdout)) 之前关闭 stdout。
请在问题中添加更多详细信息,以准确说明您在运行此代码时所看到的内容。这将有助于诊断问题。
关于c++ - windows8 - _dup,_dup2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9972669/