3

我使用 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上的一个已知问题吗?

4

1 回答 1

0

我在您的代码中看到了一个小问题。

static void releaseOutputStream(int fd)

{   fflush(stdout);
    streamDup2(fd,fileno(stdout));
    close(fd);
}

在此函数中,您不会在 dup2 调用 (fclose(stdout)) 之前关闭标准输出。

请在问题中添加更多详细信息,说明您在运行此代码时所看到的确切内容。这将有助于诊断问题。

于 2012-04-10T20:50:35.657 回答