Created
November 22, 2011 19:33
-
-
Save glejeune/1386662 to your computer and use it in GitHub Desktop.
Find a (UNIX) process in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.lang.Process; | |
| import java.io.BufferedReader; | |
| import java.io.IOException; | |
| import java.io.InputStreamReader; | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.List; | |
| class Test { | |
| static public class OsProcess { | |
| private Integer pid; | |
| private String name; | |
| public OsProcess(Integer pid, String name) { | |
| this.pid = pid; | |
| this.name = name; | |
| } | |
| public Integer getPid() { | |
| return pid; | |
| } | |
| public String getName() { | |
| return name; | |
| } | |
| @Override | |
| public String toString() { | |
| return String.format("%d : %s", pid, name); | |
| } | |
| } | |
| static public void main(String[] args) { | |
| List<OsProcess> processes = findByName(args[0]); | |
| System.out.println(processes); | |
| } | |
| static public List<OsProcess> findByName(String processNamePattern) { | |
| String cmd = "CPID=$$; ps -eo ppid,pid,command | tail -n +2 | grep \""+processNamePattern+"\" | awk -v CPID=$CPID '{PPID=$1; $1=\"\"; PID=$2; $2=\"\"; sub(/^ */, \"\"); if(CPID != PPID && CPID != PID) { print PID\"|\"$0}}'"; | |
| return find(cmd); | |
| } | |
| static private List<OsProcess> find(String command) { | |
| List<OsProcess> processes = new ArrayList<OsProcess>(); | |
| try { | |
| Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command}); | |
| BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); | |
| String line = input.readLine(); | |
| while (line != null) { | |
| List<String> data = Arrays.asList(line.split("\\|")); | |
| Integer pid = Integer.valueOf(data.get(0)); | |
| String name = data.get(1); | |
| OsProcess np = new OsProcess(pid, name); | |
| processes.add(np); | |
| line = input.readLine(); | |
| } | |
| input.close(); | |
| } catch (IOException e) { | |
| throw new RuntimeException(e); | |
| } | |
| return processes; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment