In this article, we will learn how to check whether a specific process is running on Linux in Java. There is a case where we have to check before executing the tasks whether a specific process is currently running or not.
private boolean isProcessAlreadyRunning() throws IOException{
String line;
String applicationToCheck = "mytask.jar";
boolean applicationIsRunning = false;
Process proc = Runtime.getRuntime().exec("ps -ef");
InputStream stream = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
//Parsing the input stream.
while ((line = reader.readLine()) != null) {
Pattern pattern = Pattern.compile(applicationToCheck);
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
log.info(line);
applicationIsRunning = true;
break;
}
}
return applicationIsRunning;
}