1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.tradefed.util; 18 19 import java.util.ArrayList; 20 import java.util.List; 21 22 /** 23 * Utility used to parse(USER,PID and NAME) from the "ps" command output 24 */ 25 public class PsParser { 26 27 private static final String LINE_SEPARATOR = "\\n"; 28 private static final String PROCESS_INFO_SEPARATOR = "\\s+"; 29 private static final String BAD_PID = "bad pid '-A'"; 30 31 /** 32 * Parse username, process id and process name from the ps command output and convert to list of 33 * ProcessInfo objects. 34 * 35 * @param psOutput output of "ps" command. 36 * @return list of processInfo 37 */ getProcesses(String psOutput)38 public static List<ProcessInfo> getProcesses(String psOutput) { 39 40 List<ProcessInfo> processesInfo = new ArrayList<ProcessInfo>(); 41 if (psOutput.isEmpty()) { 42 return processesInfo; 43 } 44 String processLines[] = psOutput.split(LINE_SEPARATOR); 45 46 /* 47 * (ps -A || ps) command prints "bad pid '-A'" as first line before the ps header in 48 * N and older builds so skip the first two lines. 49 */ 50 int startLineNum = 1; 51 if (processLines[0].equals(BAD_PID)) { 52 startLineNum = 2; 53 } 54 55 /* 56 * Sample output: 57 * USER PID PPID VSZ RSS WCHAN PC S NAME 58 * root 1 0 11140 1848 epoll_wait 0 S init 59 * 60 * Not collecting information other than USER,PID and NAME because they are 61 * not always printed for all the processess. 62 */ 63 for (int lineCount = startLineNum; lineCount < processLines.length; lineCount++) { 64 String processInfoStr[] = processLines[lineCount].split(PROCESS_INFO_SEPARATOR); 65 ProcessInfo psInfo = new ProcessInfo(processInfoStr[0], 66 Integer.parseInt(processInfoStr[1]), processInfoStr[processInfoStr.length - 1]); 67 processesInfo.add(psInfo); 68 } 69 return processesInfo; 70 } 71 72 } 73 74