使用JNI获取运行时进程的PID

使用JNI获取运行时进程的PID

本文介绍了使用JNI获取运行时进程的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取通过Java的Runtime.getRuntime().exec()命令启动的进程的PID.

I need to get the PID of a process which is launched via Java's Runtime.getRuntime().exec() command.

我知道如何在JNA中做到这一点.但是我真的很想使用JNI并创建自己的库.有人知道怎么做吗?

I know how to do it in JNA. But I really would like to do it with JNI and create my own libraries. Does anyone know how to do it?

import java.lang.reflect.Field;

class GetPid
{
    public native int getPid( long procHandle);

    static
    {
        System.loadLibrary("getpid");
    }

    public static void main(String args[])
    {
        try {

          Process process = Runtime.getRuntime().exec( "calc");
          Field f = process.getClass().getDeclaredField( "handle");
          f.setAccessible( true);
          long procHandle = f.getLong( process);

          System.out.println( "prochandle: " + procHandle + ", pid: " + new GetPid().getPid( procHandle));

        } catch( Exception e) {
          e.printStackTrace();
        }

    }
}

但是C部分应该是什么样子?

But what's the C part supposed to look like?

JNIEXPORT jint JNICALL
Java_GetPid_getPid(JNIEnv *env, jobject obj, jlong handle)
{
    ...

    return ???;
}

如果有人可以帮助我,那将是很棒的.我主要寻求Windows解决方案,因为您可以从过程"字段中获取Linux的PID,但我不介意是否有人可以向我展示如何在Linux/Solaris中执行此操作.

It would be great if someone could help me. I mainly seek the Windows solution, since you can get the PID for Linux from the Process field, but I wouldn't mind if someone could show me how to do this in Linux / Solaris as well.

非常感谢您!

推荐答案

知道了.就像使用这样简单:

Got it. It was as simple as using:

#define WINVER 0x0501
#define _WIN32_WINNT 0x0501

JNIEXPORT jint JNICALL
Java_GetPid_getPid(JNIEnv *env, jobject obj, jlong handle)
{
  return GetProcessId((HANDLE) handle);
}

感谢所有尝试提供帮助的人:-)

Thanks to all who tried to help :-)

这篇关于使用JNI获取运行时进程的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:46