Page 1 of 1

Process List

Posted: Mon Dec 01, 2014 7:31 pm
by danielheth
I have the following which will provide me with a list of processes currently running, their pid, ppid, cpu and command... is there any better way?

Code: Select all

;-- CHECK RUNNING PROCESS --
    Protected vCompiler = RunProgram("ps", "-axo pid,ppid,%cpu,command", "/bin", #PB_Program_Open | #PB_Program_Read)
    Protected resLength.l = 0
    Dim Results.s(0)
    
    
    If vCompiler
      WriteLog(gConfig\CommandId, #TCT_LOG_LEVEL_INFO, "Scanning running processes")
      While ProgramRunning(vCompiler)
        If AvailableProgramOutput(vCompiler)          
          ReDim Results(resLength)
          Results(resLength) = ReadProgramString(vCompiler)
          resLength = resLength + 1
        EndIf
      Wend ;"Exitcode: " + Str(ProgramExitCode(vCompiler))
      CloseProgram(vCompiler) ; Close the connection to the program
      resLength = resLength - 1
      
      
      ;Now all output is within the Results array, now we need to process to determine position and width of each column
      ;LINUX::   PID  PPID %CPU COMMAND
      ;  MAC::   PID  PPID  %CPU COMMAND
      Dim Columns.ColumnsInfo(4)
      Protected i.l = 0
      
      Columns(0)\Start = 0
      Columns(1)\Start = FindString( Results(0), "PID" ) + 3
      Columns(2)\Start = FindString( Results(0), "PPID" ) + 4
      Columns(3)\Start = FindString( Results(0), "%CPU" ) + 4
      
      Columns(0)\Length = Columns(1)\Start
      Columns(1)\Length = Columns(2)\Start - Columns(1)\Start
      Columns(2)\Length = Columns(3)\Start - Columns(2)\Start
      Columns(3)\Length = Len( Results(0) ) - Columns(3)\Start
      For i = 1 To resLength
        If ( Len( Results(i) ) - Columns(3)\Start ) > Columns(3)\Length
          Columns(3)\Length = Len( Results(i) ) - Columns(3)\Start
        EndIf
      Next
      
      ;PrintN( "Column 0::" + Columns(0)\Start + "::" + Columns(0)\Length )
      ;PrintN( "Column 1::" + Columns(1)\Start + "::" + Columns(1)\Length )
      ;PrintN( "Column 2::" + Columns(2)\Start + "::" + Columns(2)\Length )
      ;PrintN( "Column 3::" + Columns(3)\Start + "::" + Columns(3)\Length )
      
      ;PrintN( Results(0) )
      For i = 1 To resLength
        PrintN( "-----------------------" )
        ;PrintN( Results(i) )
        PrintN( " PID=" + Trim( Mid( Results(i), Columns(0)\Start, Columns(0)\Length ) ) )
        PrintN( "PPID=" + Trim( Mid( Results(i), Columns(1)\Start, Columns(1)\Length ) ) )
        PrintN( "%CPU=" + Trim( Mid( Results(i), Columns(2)\Start, Columns(2)\Length ) ) )
        PrintN( " CMD=" + Trim( Mid( Results(i), Columns(3)\Start, Columns(3)\Length ) ) )
      Next
     
    Else
      StdErr("Unable to start external application.")
    EndIf