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; }
相关文章推荐
- 【Linux调试技巧----标准输出重定向到文件】dup2和dup的妙用
- 用dup2将标准输出重定向到一个打开的文件,稍后,恢复标准输出
- APUE之dup,dup2函数重定向标准输出实例
- nohup 后台运行,以及重定向标准输出和标准错误 &/dev/null 文件
- linux 重定向 标准错误与标准输出到同一文件
- C语言如何使标准输出重定向到一个文件
- linux c 使用dup2函数将输出重定向到文件 --execl
- 将Linux 标准输出,错误输出重定向到文件
- 重定向已经运行进程的标准输出到文件的办法(通过ptrace注入代码到其他进程并运行)
- 标准输入、输出和错误和文件重定向
- 将Linux 标准输出,错误输出重定向到文件
- nohup 后台运行,以及重定向标准输出和标准错误 &/dev/null 文件
- C#中将标准输出重定向到日志文件
- 将标准输出重定向到一个文件的同时并在屏幕上显示
- Linux标准输入、输出和错误和文件重定向(转)
- C/C++-标准输入/输出重定向为文件输入/输出
- 将标准输出重定向到一个文件的同时并在屏幕上显示
- linux下通过dup2标准输出重定向查看系统进程方法(也是popen函数实现的方法)
- bash的保留文件描述符 012标准输入,输出,错误文件的重定向
- DOS命令行下如何把标准错误和标准输出重定向到同一个文件