playerken

博客园 首页 新随笔 联系 订阅 管理
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;
}

  

posted on 2013-01-25 15:00  playerken  阅读(1402)  评论(0编辑  收藏  举报