您的位置:首页 > 其它

dup和dup2重定向标准输出到文件

2013-01-25 15:00 162 查看
extern "C" int lsof_entry( int argc, char *argv[] );
bool OSRunLsof( const wxString &strTempPath )
{
// create a temp file to retrieve the lsof result.
wxString strLsofFile = OSCreateTempFileName( strTempPath + "lof" );
if( strLsofFile.IsEmpty() )
{
LogDebug( "OSRunLsof() failed to create temp lsof file." );
return false;
}
LogDebug( "OSRunLsof() successfully created temp lsof file: %s.", strLsofFile.c_str() );
wxGetApp().AddFileNameToDeleteList( strLsofFile );

bool bResult = false;

// Open the created temp file.
wxFile fileLsof( strLsofFile, wxFile::read_write );
if( fileLsof.IsOpened() )
{
// backup stdout and stderr.
int iStdout = dup(STDOUT_FILENO);
int iStderr = dup(STDERR_FILENO);
if( ( -1 != iStderr ) && ( -1 != iStdout ) )
{
int fdNull = open("/dev/null", O_RDWR);
if( -1 != fdNull )
{
// redirect stdout and stderr.
if( ( -1 != dup2( fileLsof.fd(), STDOUT_FILENO ) ) &&
( -1 != dup2( fdNull, STDERR_FILENO ) ) )
{
// format arguments: losf -i -P -n
const int ARG_NUM = 3;
char strArg0[5] = { "lsof" };
char strArg1[3] = { "-i" };
char strArg2[3] = { "-P" };
char strArg3[3] = { "-n" };
char* strArgv[ ARG_NUM + 1 ] = { strArg0, strArg1, strArg2, strArg3 };

// run lsof.
if( 0 == lsof_entry( ARG_NUM, strArgv ) )
{
bResult = true;
}

// restore stdout and stderr.
dup2( iStdout, STDOUT_FILENO );
dup2( iStderr, STDERR_FILENO );
}
else
{
LogDebug( "OSRunLsof() failed to dup2 STD_FILENO." );
}
}
else
{
LogDebug( "OSRunLsof() failed to open /dev/null." );
}

// close backup.
close( iStdout );
close( iStderr );
}
else
{
LogDebug( "OSRunLsof() failed to dup STD_FILENO." );
}
fileLsof.Close();
}
else
{
LogDebug( "OSRunLsof() failed to open temp lsof file: %s.", strLsofFile.c_str() );
}

// Process lsof file.
//if( bResult )
//{
//  // temporary process
//  wxCopyFile( strLsofFile, "/root/lsof.txt" );
//}

wxGetApp().RemoveFileNameFromDeleteList( strLsofFile );
return bResult;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: