Reputation: 10153
Here is the code of the functions:
int getStream()
{
int fd = _dup(fileno(stdout));
freopen("tmp","w",stdout);
return fd;
}
void freeStream(int fd)
{
_dup2(fd,fileno(stdout));
close(fd);
}
The code of main program:
printf(“start tets”);
int fd = getStream();
printf(“redirection”);
freeStream(fd);
This is a part of large program which uses llvm
The problem I get after freeStream(fd)
: LLVM ERROR: IO failure on output stream.
I understand that the problem is with freeStream implementation.
What do you think?
Thanks
Upvotes: 2
Views: 2517
Reputation: 754110
As Jason diagnosed, you need to fflush()
the stream (stdout
) before you close the underlying file (via the _dup2()
call).
Another problem is that there is no error checking in the code; you don't know which, if any, of your function calls are failing. At least while resolving this issue, you need to monitor both freopen()
and _dup2()
to ensure they work.
It is not clear that on Windows, you can reach behind the back of the <stdio.h>
library and change the file descriptor. On Unix, I think it would likely work - not necessarily supported, but probably it would work. But I can easily imagine ways it fails on Windows (without being certain that my imagination is not simply being to vivid).
Ultimately, I am not convinced there's a portable way to reinstate stdout
back to its original output after using freopen()
on it.
Upvotes: 2
Reputation: 32520
If you want to reliably see the text "redirection"
end up in your temporary file, you'll need to flush the buffer in stdout
before you close it to get rid of any pending writes that are buffered in the stream. To accomplish this, add this line to your freeStream
function:
void freeStream(int fd)
{
fflush(stdout); //<== add this line
_dup2(fd,fileno(stdout));
close(fd);
}
Upvotes: 3