Java Examples for java.lang.ProcessHandle

The following java examples will help you to understand the usage of java.lang.ProcessHandle. These source code samples are taken from different open source projects.

Example 1
Project: cache2k-benchmark-master  File: PlatformUtil.java View source code
/**
     * Obtain process ID via official API on Java 9.
     */
private static Long getProcessIdJava9() {
    try {
        Class c = Class.forName("java.lang.ProcessHandle");
        Method _current = c.getDeclaredMethod("current");
        Method _getPid = c.getDeclaredMethod("getPid");
        Object _handle = _current.invoke(null);
        return (Long) _getPid.invoke(_handle);
    } catch (Exception ex) {
        System.err.println("ForcedGcMemoryProfiler: error obtaining PID");
        ex.printStackTrace();
    }
    return null;
}
Example 2
Project: byte-buddy-master  File: ByteBuddyAgent.java View source code
@Override
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception should not be rethrown but trigger a fallback")
public AttachmentTypeEvaluator run() {
    try {
        if (Boolean.getBoolean(JDK_ALLOW_SELF_ATTACH)) {
            return Disabled.INSTANCE;
        } else {
            return new ForJava9CapableVm(Class.forName("java.lang.ProcessHandle").getMethod("current"), Class.forName("java.lang.ProcessHandle").getMethod("pid"));
        }
    } catch (Exception ignored) {
        return Disabled.INSTANCE;
    }
}
Example 3
Project: dumpling-master  File: PidRuntimeFactory.java View source code
private long extractPid(@Nonnull Process process) {
    Throwable problem = null;
    try {
        Method toHandle = Process.class.getMethod("toHandle");
        Object handle = toHandle.invoke(process);
        return (Long) Class.forName("java.lang.ProcessHandle").getMethod("getPid").invoke(handle);
    } catch (NoSuchMethodException e) {
    } catch (IllegalAccessException e) {
        throw new AssertionError(e);
    } catch (ClassNotFoundException e) {
        throw new AssertionError(e);
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause instanceof UnsupportedOperationException) {
            problem = cause;
        } else if (cause instanceof SecurityException) {
            problem = cause;
        } else {
            throw new AssertionError(e);
        }
    }
    // Fallback for Java6+ on unix. This is known not to work for Java8 on Windows.
    if (!"java.lang.UNIXProcess".equals(process.getClass().getName()))
        throw new UnsupportedOperationException("Unknown java.lang.Process implementation: " + process.getClass().getName(), problem);
    try {
        // Protected class
        Class<?> clazz = Class.forName("java.lang.UNIXProcess");
        Field pidField = clazz.getDeclaredField("pid");
        pidField.setAccessible(true);
        return pidField.getLong(process);
    } catch (ClassNotFoundException e) {
        throw new UnsupportedOperationException("Unable to find java.lang.UNIXProcess", e);
    } catch (NoSuchFieldException e) {
        throw new UnsupportedOperationException("Unable to find java.lang.UNIXProcess.pid", e);
    } catch (IllegalAccessException e) {
        throw new UnsupportedOperationException("Unable to access java.lang.UNIXProcess.pid", e);
    }
}
Example 4
Project: openjdk-master  File: Basic.java View source code
public static void main(String args[]) throws Throwable {
    String action = args[0];
    if (action.equals("sleep")) {
        Thread.sleep(10 * 60 * 1000L);
    } else if (action.equals("pid")) {
        System.out.println(ProcessHandle.current().getPid());
    } else if (action.equals("testIO")) {
        String expected = "standard input";
        char[] buf = new char[expected.length() + 1];
        int n = new InputStreamReader(System.in).read(buf, 0, buf.length);
        if (n != expected.length())
            System.exit(5);
        if (!new String(buf, 0, n).equals(expected))
            System.exit(5);
        System.err.print("standard error");
        System.out.print("standard output");
    } else if (action.equals("testInheritIO") || action.equals("testRedirectInherit")) {
        List<String> childArgs = new ArrayList<String>(javaChildArgs);
        childArgs.add("testIO");
        ProcessBuilder pb = new ProcessBuilder(childArgs);
        if (action.equals("testInheritIO"))
            pb.inheritIO();
        else
            redirectIO(pb, INHERIT, INHERIT, INHERIT);
        ProcessResults r = run(pb);
        if (!r.out().equals(""))
            System.exit(7);
        if (!r.err().equals(""))
            System.exit(8);
        if (r.exitValue() != 0)
            System.exit(9);
    } else if (action.equals("System.getenv(String)")) {
        String val = System.getenv(args[1]);
        printUTF8(val == null ? "null" : val);
    } else if (action.equals("System.getenv(\\u1234)")) {
        String val = System.getenv("ሴ");
        printUTF8(val == null ? "null" : val);
    } else if (action.equals("System.getenv()")) {
        printUTF8(getenvAsString(System.getenv()));
    } else if (action.equals("ArrayOOME")) {
        Object dummy;
        switch(new Random().nextInt(3)) {
            case 0:
                dummy = new Integer[Integer.MAX_VALUE];
                break;
            case 1:
                dummy = new double[Integer.MAX_VALUE];
                break;
            case 2:
                dummy = new byte[Integer.MAX_VALUE][];
                break;
            default:
                throw new InternalError();
        }
    } else if (action.equals("pwd")) {
        printUTF8(new File(System.getProperty("user.dir")).getCanonicalPath());
    } else if (action.equals("print4095")) {
        print4095(System.out, (byte) '!');
        print4095(System.err, (byte) 'E');
        System.exit(5);
    } else if (action.equals("OutErr")) {
        // You might think the system streams would be
        // buffered, and in fact they are implemented using
        // BufferedOutputStream, but each and every print
        // causes immediate operating system I/O.
        System.out.print("out");
        System.err.print("err");
        System.out.print("out");
        System.err.print("err");
    } else if (action.equals("null PATH")) {
        equal(System.getenv("PATH"), null);
        check(new File("/bin/true").exists());
        check(new File("/bin/false").exists());
        ProcessBuilder pb1 = new ProcessBuilder();
        ProcessBuilder pb2 = new ProcessBuilder();
        pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
        ProcessResults r;
        for (final ProcessBuilder pb : new ProcessBuilder[] { pb1, pb2 }) {
            pb.command("true");
            equal(run(pb).exitValue(), True.exitValue());
            pb.command("false");
            equal(run(pb).exitValue(), False.exitValue());
        }
        if (failed != 0)
            throw new Error("null PATH");
    } else if (action.equals("PATH search algorithm")) {
        equal(System.getenv("PATH"), "dir1:dir2:");
        check(new File("/bin/true").exists());
        check(new File("/bin/false").exists());
        String[] cmd = { "prog" };
        ProcessBuilder pb1 = new ProcessBuilder(cmd);
        ProcessBuilder pb2 = new ProcessBuilder(cmd);
        ProcessBuilder pb3 = new ProcessBuilder(cmd);
        pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
        pb3.environment().remove("PATH");
        for (final ProcessBuilder pb : new ProcessBuilder[] { pb1, pb2, pb3 }) {
            try {
                // Not on PATH at all; directories don't exist
                try {
                    pb.start();
                    fail("Expected IOException not thrown");
                } catch (IOException e) {
                    String m = e.getMessage();
                    if (EnglishUnix.is() && !matches(m, "No such file"))
                        unexpected(e);
                } catch (Throwable t) {
                    unexpected(t);
                }
                // Not on PATH at all; directories exist
                new File("dir1").mkdirs();
                new File("dir2").mkdirs();
                try {
                    pb.start();
                    fail("Expected IOException not thrown");
                } catch (IOException e) {
                    String m = e.getMessage();
                    if (EnglishUnix.is() && !matches(m, "No such file"))
                        unexpected(e);
                } catch (Throwable t) {
                    unexpected(t);
                }
                // Can't execute a directory -- permission denied
                // Report EACCES errno
                new File("dir1/prog").mkdirs();
                checkPermissionDenied(pb);
                // continue searching if EACCES
                copy("/bin/true", "dir2/prog");
                equal(run(pb).exitValue(), True.exitValue());
                new File("dir1/prog").delete();
                new File("dir2/prog").delete();
                new File("dir2/prog").mkdirs();
                copy("/bin/true", "dir1/prog");
                equal(run(pb).exitValue(), True.exitValue());
                // Check empty PATH component means current directory.
                //
                // While we're here, let's test different kinds of
                // Unix executables, and PATH vs explicit searching.
                new File("dir1/prog").delete();
                new File("dir2/prog").delete();
                for (String[] command : new String[][] { new String[] { "./prog" }, cmd }) {
                    pb.command(command);
                    File prog = new File("./prog");
                    // "Normal" binaries
                    copy("/bin/true", "./prog");
                    equal(run(pb).exitValue(), True.exitValue());
                    copy("/bin/false", "./prog");
                    equal(run(pb).exitValue(), False.exitValue());
                    prog.delete();
                    // Interpreter scripts with #!
                    setFileContents(prog, "#!/bin/true\n");
                    prog.setExecutable(true);
                    equal(run(pb).exitValue(), True.exitValue());
                    prog.delete();
                    setFileContents(prog, "#!/bin/false\n");
                    prog.setExecutable(true);
                    equal(run(pb).exitValue(), False.exitValue());
                    // Traditional shell scripts without #!
                    setFileContents(prog, "exec /bin/true\n");
                    prog.setExecutable(true);
                    equal(run(pb).exitValue(), True.exitValue());
                    prog.delete();
                    setFileContents(prog, "exec /bin/false\n");
                    prog.setExecutable(true);
                    equal(run(pb).exitValue(), False.exitValue());
                    prog.delete();
                }
                // Test Unix interpreter scripts
                File dir1Prog = new File("dir1/prog");
                dir1Prog.delete();
                pb.command(new String[] { "prog", "world" });
                setFileContents(dir1Prog, "#!/bin/echo hello\n");
                checkPermissionDenied(pb);
                dir1Prog.setExecutable(true);
                equal(run(pb).out(), "hello dir1/prog world\n");
                equal(run(pb).exitValue(), True.exitValue());
                dir1Prog.delete();
                pb.command(cmd);
                // Test traditional shell scripts without #!
                setFileContents(dir1Prog, "/bin/echo \"$@\"\n");
                pb.command(new String[] { "prog", "hello", "world" });
                checkPermissionDenied(pb);
                dir1Prog.setExecutable(true);
                equal(run(pb).out(), "hello world\n");
                equal(run(pb).exitValue(), True.exitValue());
                dir1Prog.delete();
                pb.command(cmd);
                // If prog found on both parent and child's PATH,
                // parent's is used.
                new File("dir1/prog").delete();
                new File("dir2/prog").delete();
                new File("prog").delete();
                new File("dir3").mkdirs();
                copy("/bin/true", "dir1/prog");
                copy("/bin/false", "dir3/prog");
                pb.environment().put("PATH", "dir3");
                equal(run(pb).exitValue(), True.exitValue());
                copy("/bin/true", "dir3/prog");
                copy("/bin/false", "dir1/prog");
                equal(run(pb).exitValue(), False.exitValue());
            } finally {
                // cleanup
                new File("dir1/prog").delete();
                new File("dir2/prog").delete();
                new File("dir3/prog").delete();
                new File("dir1").delete();
                new File("dir2").delete();
                new File("dir3").delete();
                new File("prog").delete();
            }
        }
        if (failed != 0)
            throw new Error("PATH search algorithm");
    } else
        throw new Error("JavaChild invocation error");
}
Example 5
Project: java-virtual-machine-master  File: ByteBuddyAgent.java View source code
@Override
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception should not be rethrown but trigger a fallback")
public AttachmentTypeEvaluator run() {
    try {
        if (Boolean.getBoolean(JDK_ALLOW_SELF_ATTACH)) {
            return Disabled.INSTANCE;
        } else {
            return new ForJava9CapableVm(Class.forName("java.lang.ProcessHandle").getMethod("current"), Class.forName("java.lang.ProcessHandle").getMethod("pid"));
        }
    } catch (Exception ignored) {
        return Disabled.INSTANCE;
    }
}
Example 6
Project: hibernate-demos-master  File: ProcessIdProvider.java View source code
public ProcessIdDescriptor getPid() {
    long pid = ProcessHandle.current().getPid();
    return new ProcessIdDescriptor(pid, "ProcessHandle");
}