我试图在Mac上获取Java进程的pid。该进程应列出目录中的项目,然后打印进程的pid。在调整了此link的unix示例后,我仍然在pid变量上出现错误(无法找到符号)。
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();
}
}
}
答案 0 :(得分:1)
编译错误,pid
应在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);