一.写JAVA代码
private static final Logger log = LoggerFactory.getLogger(LinuxProcess.class);
public MacOsXProcess() {
}
static {
new FileUtils().loadLibrary("libmacjni.jnilib");
}
@Override
public List<Integer> getPids(int processId, String host) {
List<Integer> children = new ArrayList<>();
Map<Integer, Integer> parentPidMap = getParentPidMap(host);
Map<Integer, Integer> childrenParentPidMap = new HashMap<>();
for (Map.Entry<Integer, Integer> entry : parentPidMap.entrySet()) {
childrenParentPidMap.put(entry.getValue(), entry.getKey());
}
Queue<Integer> queue = new LinkedList<>();
queue.add(processId);
while (!queue.isEmpty()) {
Integer currentPid = queue.poll();
if (childrenParentPidMap.containsKey(currentPid)) {
children.add(childrenParentPidMap.get(currentPid));
queue.add(childrenParentPidMap.get(currentPid));
}
}
log.info("Macos system ,get pids ={}", children);
return children;
}
@Override
public Map<Integer, Integer> getParentPidMap(String host) {
Map<Integer, Integer> result = new HashMap<>();
ProcessInfo[] processInfos = processTable();
for (ProcessInfo processInfo : processInfos) {
result.put(processInfo.getPid(), processInfo.getParentPid());
}
return result;
}
@Override
public Integer getParentPid(int processId, String host) {
return getParentPidMap(host).get(processId);
}
public native ProcessInfo[] processTable();
二.将项目编译为clss文件(maven项目class文件已经在target目录下)
- 在项目的根目录下执行命令,产生的是MacOsXProcess.h文件
javah -classpath /Users/xxx/IdeaProjects/xxx/target/classes org.apache.xxx.common.pid.process.MacOsXProcess
三. 编写.c文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_apache_xxxx_common_pid_process_MacOsXProcess */
#ifndef _Included_org_apache_xxxx_common_pid_process_MacOsXProcess
#define _Included_org_apache_xxxx_common_pid_process_MacOsXProcess
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_apache_xxxx_common_pid_process_MacOsXProcess
* Method: processTable
* Signature: ()[Lorg/apache/xxxx/common/pid/core/ProcessInfo;
*/
JNIEXPORT jobjectArray JNICALL Java_org_apache_xxxx_common_pid_process_MacOsXProcess_processTable
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
四.编译c文件
- 在MacOsXProcess.h中会有一句
#include <jni.h>
jni.h是jdk中C语言库的头文件,在编译.c的时候需要指定jni.h的所在。在Mac OX中他所在的位置是:
${JAVA_HOME}/include
使用gcc编译
gcc -I/Library/Java/JavaVirtualMachines/jdk1.8.0_301.jdk/Contents/Home/include -c MacOsXProcess.c
就可以得到一个编译好的文件 MacOsXProcess.o,下面需要把.o文件打包成动态库。
五.将.o文件打包为动态库
gcc -dynamiclib -o libmacjni.jnilib MacOsXProcess.o
至此,java代码就可以调用c语言了。