Original question : I successfully found the pid of a process using the following code. I'm looking to get the id of the child process, and here I believed I would achieve it by finding the id of the InputStreamReader. I'm not going about this the right way, however, as I'm unable to pinpoint which part of my code would correctly return an id of the child process.
Update and more info : My goal is keep track of the parent process id, announce the creation of a child process with it's ID and the parent's ID. Finally, announce the termination of the child process.
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
class processes {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("/bin/ls");
final InputStream is = p.getInputStream();
final InputStream was = p.getInputStream();
Thread t = new Thread(new Runnable() {
public void run() {
InputStreamReader isr = new InputStreamReader(is);
InputStreamReader wasr = new InputStreamReader(was);
int isid = 0;
int ch;
if(isr.getClass().getName().equals("java.lang.UNIXProcess")) {
/* get the PID on unix/linux systems */
try {
Field i = isr.getClass().getDeclaredField("pid");
i.setAccessible(true);
isid = i.getInt(isr);
System.out.println("is process");
}
catch (Throwable e) {
}
}
try {
System.out.println(isid);
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
while ((ch = wasr.read()) != -1) {
System.out.print((char) ch);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
p.waitFor();
t.join();
int pid = 0;
//final int isid = 0;
//int isid = 0;
if(p.getClass().getName().equals("java.lang.UNIXProcess")) {
/* get the PID on unix/linux systems */
try {
Field f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
//i.setAccessible(true);
pid = f.getInt(p);
//isid = i.getInt(is);
}
catch (Throwable e) {
}
}
System.out.println("Process p " + pid + " terminates.");
//System.out.println(pid);
} catch (Exception e) {
e.printStackTrace();
}
}
}