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

本文介绍了如何通过C++代码实现类似lsof命令的功能,用于记录系统中所有文件的打开状态,并通过创建临时文件来获取这些信息。详细解释了如何在程序中操作文件,包括创建临时文件、复制文件内容到指定位置以及处理文件打开状态的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

  

转载于:https://www.cnblogs.com/playerken/archive/2013/01/25/2876669.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值