Re: dup2
On Tuesday, 22 April 2014 09:35:06 UTC+1, Hongliang Wang wrote:
Hell all,
I was trying to redirect stdout to a file by using dup2. First I followed=
microsoft example: http://msdn.microsoft.com/en-us/library/8syseb29.aspx
it just works fine.
Then I tried to implement this in my own class (ABCLog) but stdout is not=
captured. I cannot figure it out. The only reason I could think of is that=
main() is in main.cpp while class ABCLog are in separate files (ABCLog.cpp=
and ABCLog.h). Could anybody confirm this please?
int main(int argc, char *argv[])
{
ABCLog *log = new ABCLog();
puts("in main");
fflush( stdout );
delete log;
return 0;
}
ABCLog::ABCLog(const char *logFileName)
{
old = _dup(1); /* "old" refers to stdout */
if(old == -1) {
perror(ERR_000104_DUP);
exit(1);
}
if( fopen_s( &logFile, logFileName, "a" ) != 0 ) {
fprintf(stderr, ERR_000105_LOG_FILE_OPEN, logFileName);
exit( 1 );
}
if( -1 == _dup2( _fileno( logFile ), 1 ) ) {
perror( ERR_000106_DUP2 );
exit( 1 );
}
puts("in ABCLog");
fflush(stdout);
}
/**
* Destructor
*/
ABCLog::~ABCLog()
{
_dup2( old, 1 );
_flushall();
m_stream.close();
}
Other people have explained this, but perhaps not clearly enough, so I'll h=
ave a go.
In main, the object is brought into existence, but it then is destroyed wit=
hout the program doing anything to it. Strange as it may seem, this means t=
hat the compiler is allowed to not create the object at all. So you don't g=
et the side effects from the constructor and the destructor that you were h=
oping for.
So - is the constructor actually being run? You could test this for example=
by putting an output command or a beep into the constructor - does the com=
puter actually beep when you run it?
From your last reply, it seems that you are answering the question of wheth=
er the constructor runs simply by looking at the code and saying "but surel=
y it must do?" Don't do that - actually test it.
Hope this helps.
Paul.