提交 5ccb8ad6 authored 作者: 吕本才's avatar 吕本才

修改获取pid方法引用

上级 3ad56ca2
package com.ruoshui.core.enums.util;
import com.ruoshui.core.enums.log.JobLogger;
import com.ruoshui.core.enums.thread.JobThread;
import com.sun.jna.Platform;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
/**
* ProcessUtil
*
* @author jingwk
* @version 1.0
* @since 2019/11/09
*/
public class ProcessUtil {
private static Logger logger = LoggerFactory.getLogger(JobThread.class);
public static String getProcessId(Process process) {
long pid = -1;
Field field;
if (Platform.isWindows()) {
try {
field = process.getClass().getDeclaredField("handle");
field.setAccessible(true);
pid = Kernel32.INSTANCE.GetProcessId((Long) field.get(process));
} catch (Exception ex) {
logger.error("get process id for windows error {0}", ex);
}
} else if (Platform.isLinux() || Platform.isAIX()) {
try {
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
field = clazz.getDeclaredField("pid");
field.setAccessible(true);
pid = (Integer) field.get(process);
} catch (Throwable e) {
logger.error("get process id for unix error {0}", e);
}
}
return String.valueOf(pid);
}
/**
* 关闭Linux进程
*
* @param pid 进程的PID
*/
public static boolean killProcessByPid(String pid) {
if (StringUtils.isEmpty(pid) || "-1".equals(pid)) {
throw new RuntimeException("Pid ==" + pid);
}
Process process = null;
BufferedReader reader = null;
String command = "";
boolean result;
if (Platform.isWindows()) {
command = "cmd.exe /c taskkill /PID " + pid + " /F /T ";
} else if (Platform.isLinux() || Platform.isAIX()) {
command = "kill " + pid;
}
try {
//杀掉进程
process = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
JobLogger.log(line);
}
result = true;
} catch (Exception e) {
logger.error("kill pid error {0}", e);
result = false;
} finally {
if (process != null) {
process.destroy();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
logger.error("reader close error {0}", e);
}
}
}
return result;
}
}
......@@ -4,6 +4,7 @@ package com.ruoshui.core.enums.util;
import com.ruoshui.core.enums.biz.model.HandleProcessCallbackParam;
import com.ruoshui.core.enums.log.JobLogger;
import com.ruoshui.core.enums.thread.ProcessCallbackThread;
import com.ruoshui.core.util.ProcessUtil;
import java.io.FileOutputStream;
import java.io.IOException;
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论