Get Unix processid for multiple instance of same java program
I have a scenario in which i will invoke a java program with some cmd line arguments. Once i invoke that program i have to capture unix processid for that particular execution. Pls Note that the same java program will be invoked simulatenoulsy with different param value. For very execution, I have to capture the appropriately processid (I will use this processid to kill execution of particlar instance if required).
This my hot requirement. Pls give a solution or other alternative
[498 byte] By [
IamMahesha] at [2007-11-26 22:14:00]

# 1
Hello Mahesh...
first of all you don't need the process id to kill from the shell, you can kill it from the code, try this...
/**
* A simple class this is supposed to be your real application...
*/
import javax.swing.*;
public class MaheshClass {
public static void main(String a[]) {
JOptionPane.showMessageDialog(null, "hello");
}
}
/**
*The test class
*/
import java.io.IOException;
import java.util.Hashtable;
import java.util.Enumeration;
public class test {
static Hashtable<String, Process> processesHashtable = new Hashtable<String, Process>();
public static void main(String[] a) {
for (int i = 0; i < 4; i++) {
createNewProcess();
}
Enumeration<String> enu = processesHashtable.keys();
while (enu.hasMoreElements()) {
System.out.println(enu.nextElement());
/*
Prints the processes names, actually toString()s, the output is somethig like this...
java.lang.ProcessImpl@9304b1
java.lang.ProcessImpl@190d11
java.lang.ProcessImpl@de6ced
java.lang.ProcessImpl@a90653
*/
}
kill("java.lang.ProcessImpl@a90653"); // kill last process
}
/**
* Creates new processes of your application and adds their name to the hashtable
*/
public static void createNewProcess() {
try {
Process process = Runtime.getRuntime().exec("java MaheshClass");
processesHashtable.put(process.toString(), process); // add the process and its toString to use it as its name
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Kills the process using its name (the key from the hashtable) to kill it.
*/
public static void kill(String processName) {
processesHashtable.get(processName).destroy();
}
}