Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created February 27, 2016 05:57
Show Gist options
  • Save gabhi/6c3bd56f02ae2c63ad21 to your computer and use it in GitHub Desktop.
Save gabhi/6c3bd56f02ae2c63ad21 to your computer and use it in GitHub Desktop.
Grep ProcessId for Process From Java
import org.zeroturnaround.exec.ProcessExecutor;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* Created by agaikwad on 2/26/16.
*/
public class GrepProcessIdProcessFromJava {
public static void main(String[] args) {
String pid = grepProcessId("tomcat");
System.out.println("----");
System.out.println("Process Id: " + pid);
System.out.println("----");
}
private static String grepProcessId(String processName) {
String processId = "";
try {
processId = new ProcessExecutor()
.command("/bin/sh",
"-c",
"ps -e -o pid,args | grep '" + processName + "' | grep -v 'grep' | awk '{print $1}'")
.readOutput(true)
.execute()
.outputUTF8();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return processId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment