如何获得我刚刚在java程序中启动的进程的PID?

问题描述 投票:65回答:16

我已经开始使用以下代码进行处理

 ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
 try {
     Process p = pb.start();       
 } 
 catch (IOException ex) {}

现在我需要知道我刚刚开始的进程的pid。

java process pid processbuilder
16个回答
25
投票

这个页面有HOWTO:

http://www.golesny.de/p/code/javagetpid

在Windows上:

Runtime.exec(..)

返回“java.lang.Win32Process”)或“java.lang.ProcessImpl”的实例

两者都有一个私人领域“句柄”。

这是该过程的OS句柄。您将不得不使用此+ Win32 API来查询PID。该页面详细介绍了如何执行此操作。


0
投票

没有一个简单的解决方案。我过去做的方法是启动另一个进程,在类Unix系统上运行ps命令,或在Windows上运行tasklist命令,然后为我想要的PID解析该命令的输出。实际上,我最终将该代码放入一个单独的shell脚本中,用于每个刚刚返回PID的平台,这样我就可以保持Java片段尽可能独立于平台。这对于短期任务不起作用,但对我来说这不是问题。


0
投票

jnr-process项目提供此功能。

它是jruby使用的java本机运行时的一部分,可以被视为未来java-FFI的原型


0
投票

我相信唯一可行的方法是通过另一个(父)Java进程运行(子)进程,这将通知我父进程的实际PID。子进程可以是任何东西。

这个包装器的代码是

package com.panayotis.wrapper;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.directory(new File(System.getProperty("user.dir")));
        pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        pb.redirectError(ProcessBuilder.Redirect.INHERIT);
        pb.start().waitFor();
    }
}

要使用它,只需使用此文件创建一个jar文件,并使用命令参数调用它:

String java = System.getProperty("java.home") + separator + "bin" + separator + "java.exe";
String jar_wrapper = "path\\of\\wrapper.jar";

String[] args = new String[]{java, "-cp", jar_wrapper, "com.panayotis.wrapper.Main", actual_exec_args...);

0
投票

如果可移植性不是一个问题,并且您只是想在使用经过测试且已知适用于所有现代版Windows的代码时在Windows上获得pid而不会有太多麻烦,您可以使用kohsuke的winp库。它也可以在Maven Central上使用,方便消费。

Process process = //...;
WinProcess wp = new WinProcess(process);
int pid = wp.getPid();

0
投票

有一个开源库有这样的功能,它有跨平台实现:https://github.com/OpenHFT/Java-Thread-Affinity

获取PID可能有点过分,但如果你想要其他东西,如CPU和线程ID,特别是线程亲和力,它可能就足够了。

要获取当前线程的PID,只需调用Affinity.getAffinityImpl().getProcessId()

这是使用JNA实现的(请参阅arcsin的回答)。


0
投票

一种解决方案是使用平台提供的特殊工具:

private static String invokeLinuxPsProcess(String filterByCommand) {
    List<String> args = Arrays.asList("ps -e -o stat,pid,unit,args=".split(" +"));
    // Example output:
    // Sl   22245 bpds-api.service                /opt/libreoffice5.4/program/soffice.bin --headless
    // Z    22250 -                               [soffice.bin] <defunct>

    try {
        Process psAux = new ProcessBuilder(args).redirectErrorStream(true).start();
        try {
            Thread.sleep(100); // TODO: Find some passive way.
        } catch (InterruptedException e) { }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(psAux.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.contains(filterByCommand))
                    continue;
                String[] parts = line.split("\\w+");
                if (parts.length < 4)
                    throw new RuntimeException("Unexpected format of the `ps` line, expected at least 4 columns:\n\t" + line);
                String pid = parts[1];
                return pid;
            }
        }
    }
    catch (IOException ex) {
        log.warn(String.format("Failed executing %s: %s", args, ex.getMessage()), ex);
    }
    return null;
}

免责声明:未经测试,但您明白了:

  • 调用ps列出进程,
  • 找到你的那个,因为你知道你启动它的命令。
  • 如果有多个进程使用相同的命令,您可以: 添加另一个伪参数来区分它们 依靠增加的PID(不是真的安全,不是并发) 检查进程创建的时间(可能太粗糙而无法真正区分,也不能并发) 添加一个特定的环境变量,并将其与ps一起列出。

0
投票

对于GNU / Linux和MacOS(或者通常类似UNIX)系统,我使用了以下方法,该方法工作正常:

private int tryGetPid(Process process)
{
    if (process.getClass().getName().equals("java.lang.UNIXProcess"))
    {
        try
        {
            Field f = process.getClass().getDeclaredField("pid");
            f.setAccessible(true);
            return f.getInt(process);
        }
        catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e)
        {
        }
    }

    return 0;
}

24
投票

目前还没有公共API。见Sun Bug 4244896,Sun Bug 4250622

作为解决方法:

Runtime.exec(...)

返回一个类型的Object

java.lang.Process

Process类是抽象的,你得到的是Process的一些子类,它是为你的操作系统设计的。例如在Mac上,它返回java.lang.UnixProcess,它有一个名为pid的私有字段。使用Reflection,您可以轻松获得此字段的值。这无疑是一个黑客,但它可能会有所帮助。无论如何你需要什么PID


22
投票

由于Java 9类Process有新方法long pid(),所以它就像它一样简单

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
try {
    Process p = pb.start();
    long pid = p.pid();      
} catch (IOException ex) {
    // ...
}

19
投票

在Unix系统(Linux和Mac)

 public static synchronized long getPidOfProcess(Process p) {
    long pid = -1;

    try {
      if (p.getClass().getName().equals("java.lang.UNIXProcess")) {
        Field f = p.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        pid = f.getLong(p);
        f.setAccessible(false);
      }
    } catch (Exception e) {
      pid = -1;
    }
    return pid;
  }

13
投票

在您的库中包含jna(“JNA”和“JNA平台”)并使用此功能:

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT;
import java.lang.reflect.Field;

public static long getProcessID(Process p)
    {
        long result = -1;
        try
        {
            //for windows
            if (p.getClass().getName().equals("java.lang.Win32Process") ||
                   p.getClass().getName().equals("java.lang.ProcessImpl")) 
            {
                Field f = p.getClass().getDeclaredField("handle");
                f.setAccessible(true);              
                long handl = f.getLong(p);
                Kernel32 kernel = Kernel32.INSTANCE;
                WinNT.HANDLE hand = new WinNT.HANDLE();
                hand.setPointer(Pointer.createConstant(handl));
                result = kernel.GetProcessId(hand);
                f.setAccessible(false);
            }
            //for unix based operating systems
            else if (p.getClass().getName().equals("java.lang.UNIXProcess")) 
            {
                Field f = p.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                result = f.getLong(p);
                f.setAccessible(false);
            }
        }
        catch(Exception ex)
        {
            result = -1;
        }
        return result;
    }

您还可以从here下载here和JNA平台的JNA。


8
投票

我想我找到了一个解决方案,在大多数平台上工作时看起来非常防弹。这是一个想法:

  1. 创建在生成新进程/终止进程之前获取的JVM范围的互斥锁
  2. 使用与平台相关的代码来获取JVM进程的子进程列表+ pids
  3. 产生新的过程
  4. 获取子进程+ pid的新列表,并与之前的列表进行比较。新的是你的家伙。

由于您只检查子进程,因此不能被同一台计算机中的某些其他进程所冤枉。 JVM范围的互斥锁比允许您确定新进程是正确的。

读取子进程列表比从进程对象获取PID更简单,因为它不需要在Windows上进行WIN API调用,更重要的是,它已经在几个库中完成了。

下面是使用JavaSysMon库实现上述想法。它

class UDKSpawner {

    private int uccPid;
    private Logger uccLog;

    /**
     * Mutex that forces only one child process to be spawned at a time. 
     * 
     */
    private static final Object spawnProcessMutex = new Object();

    /**
     * Spawns a new UDK process and sets {@link #uccPid} to it's PID. To work correctly,
     * the code relies on the fact that no other method in this JVM runs UDK processes and
     * that no method kills a process unless it acquires lock on spawnProcessMutex.
     * @param procBuilder
     * @return 
     */
    private Process spawnUDK(ProcessBuilder procBuilder) throws IOException {
        synchronized (spawnProcessMutex){            
            JavaSysMon monitor = new JavaSysMon();
            DirectUDKChildProcessVisitor beforeVisitor = new DirectUDKChildProcessVisitor();
            monitor.visitProcessTree(monitor.currentPid(), beforeVisitor);
            Set<Integer> alreadySpawnedProcesses = beforeVisitor.getUdkPids();

            Process proc = procBuilder.start();

            DirectUDKChildProcessVisitor afterVisitor = new DirectUDKChildProcessVisitor();
            monitor.visitProcessTree(monitor.currentPid(), afterVisitor);
            Set<Integer> newProcesses = afterVisitor.getUdkPids();

            newProcesses.removeAll(alreadySpawnedProcesses);

            if(newProcesses.isEmpty()){
                uccLog.severe("There is no new UKD PID.");
            }
            else if(newProcesses.size() > 1){
                uccLog.severe("Multiple new candidate UDK PIDs");
            } else {
                uccPid = newProcesses.iterator().next();
            }
            return proc;
        }
    }    

    private void killUDKByPID(){
        if(uccPid < 0){
            uccLog.severe("Cannot kill UCC by PID. PID not set.");
            return;
        }
        synchronized(spawnProcessMutex){
            JavaSysMon monitor = new JavaSysMon();
            monitor.killProcessTree(uccPid, false);
        }
    }

    private static class DirectUDKChildProcessVisitor implements ProcessVisitor {
        Set<Integer> udkPids = new HashSet<Integer>();

        @Override
        public boolean visit(OsProcess op, int i) {
            if(op.processInfo().getName().equals("UDK.exe")){
                udkPids.add(op.processInfo().getPid());
            }
            return false;
        }

        public Set<Integer> getUdkPids() {
            return udkPids;
        }
    }
}

3
投票

在我的测试中,所有IMPL类都有“pid”字段。这对我有用:

public static int getPid(Process process) {
    try {
        Class<?> cProcessImpl = process.getClass();
        Field fPid = cProcessImpl.getDeclaredField("pid");
        if (!fPid.isAccessible()) {
            fPid.setAccessible(true);
        }
        return fPid.getInt(process);
    } catch (Exception e) {
        return -1;
    }
}

只需确保返回的值不是-1。如果是,则解析ps的输出。


2
投票

我使用了一种非可移植的方法从Process对象中检索UNIX PID,这非常容易理解。

步骤1:使用一些Reflection API调用来识别目标服务器JRE上的Process实现类(请记住,Process是一个抽象类)。如果你的UNIX实现和我的一样,你会看到一个实现类,它有一个名为pid的属性,它包含进程的PID。这是我使用的日志代码。

    //--------------------------------------------------------------------
    // Jim Tough - 2014-11-04
    // This temporary Reflection code is used to log the name of the
    // class that implements the abstract Process class on the target
    // JRE, all of its 'Fields' (properties and methods) and the value
    // of each field.
    //
    // I only care about how this behaves on our UNIX servers, so I'll
    // deploy a snapshot release of this code to a QA server, run it once,
    // then check the logs.
    //
    // TODO Remove this logging code before building final release!
    final Class<?> clazz = process.getClass();
    logger.info("Concrete implementation of " + Process.class.getName() +
            " is: " + clazz.getName());
    // Array of all fields in this class, regardless of access level
    final Field[] allFields = clazz.getDeclaredFields();
    for (Field field : allFields) {
        field.setAccessible(true); // allows access to non-public fields
        Class<?> fieldClass = field.getType();
        StringBuilder sb = new StringBuilder(field.getName());
        sb.append(" | type: ");
        sb.append(fieldClass.getName());
        sb.append(" | value: [");
        Object fieldValue = null;
        try {
            fieldValue = field.get(process);
            sb.append(fieldValue);
            sb.append("]");
        } catch (Exception e) {
            logger.error("Unable to get value for [" +
                    field.getName() + "]", e);
        }
        logger.info(sb.toString());
    }
    //--------------------------------------------------------------------

第2步:根据您从Reflection日志记录中获取的实现类和字段名称,编写一些代码来挑选Process实现类,并使用Reflection API从中检索PID。以下代码适用于我的UNIX风格。你可能需要调整EXPECTED_IMPL_CLASS_NAMEEXPECTED_PID_FIELD_NAME常量才能使它适合你。

/**
 * Get the process id (PID) associated with a {@code Process}
 * @param process {@code Process}, or null
 * @return Integer containing the PID of the process; null if the
 *  PID could not be retrieved or if a null parameter was supplied
 */
Integer retrievePID(final Process process) {
    if (process == null) {
        return null;
    }

    //--------------------------------------------------------------------
    // Jim Tough - 2014-11-04
    // NON PORTABLE CODE WARNING!
    // The code in this block works on the company UNIX servers, but may
    // not work on *any* UNIX server. Definitely will not work on any
    // Windows Server instances.
    final String EXPECTED_IMPL_CLASS_NAME = "java.lang.UNIXProcess";
    final String EXPECTED_PID_FIELD_NAME = "pid";
    final Class<? extends Process> processImplClass = process.getClass();
    if (processImplClass.getName().equals(EXPECTED_IMPL_CLASS_NAME)) {
        try {
            Field f = processImplClass.getDeclaredField(
                    EXPECTED_PID_FIELD_NAME);
            f.setAccessible(true); // allows access to non-public fields
            int pid = f.getInt(process);
            return pid;
        } catch (Exception e) {
            logger.warn("Unable to get PID", e);
        }
    } else {
        logger.warn(Process.class.getName() + " implementation was not " +
                EXPECTED_IMPL_CLASS_NAME + " - cannot retrieve PID" +
                " | actual type was: " + processImplClass.getName());
    }
    //--------------------------------------------------------------------

    return null; // If PID was not retrievable, just return null
}

1
投票

这不是一般答案。

但是:某些程序(尤其是服务和长期运行的程序)创建(或提供创建,可选)“pid文件”。

例如,LibreOffice提供--pidfile={file},请参阅docs

我正在寻找Java / Linux解决方案的相当一段时间,但PID(在我的情况下)就在手边。

© www.soinside.com 2019 - 2024. All rights reserved.