简体   繁体   中英

PID of Java process on Mac

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();
       }
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM