Reputation: 1025
I'm trying to get the pid of a Java process on a Mac. The process should list the items in the directory, then print the pid of the process. After adapting the unix example from this link, i still have an error (cannot find symbol) on the pid variable.
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();
Thread t = new Thread(new Runnable() {
public void run() {
InputStreamReader isr = new InputStreamReader(is);
int ch;
try {
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
p.waitFor();
t.join();
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);
int pid = f.getInt(p);
}
catch (Throwable e) {
}
}
System.out.println("Child Complete : " + pid);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 357
Reputation:
There was a compilation error, pid
should be declared outside the if
:
int pid = 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);
pid = f.getInt(p);
}
catch (Throwable e) {
}
}
System.out.println("Child Complete : " + pid);
Upvotes: 1