进程"/>
java采用Process.destroy无法停止子进程
问题描述
当前的应用场景是,采用java执行一个python脚本,该脚本是一个机器学习算法,在训练中会比较耗时。在某些场景下,需要采用java的进程主动停止该python进程。采用如下思路进行该逻辑实现。
一种错误的实现
启动进程
ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", command);TaskExecutor executor = privpyClient.getTaskExecutor(requestId);builder.redirectErrorStream(true);log.info("{} enter running the code: {}", requestId, command);Process process = null;try {process = builder.start();if (Objects.nonNull(executor)) {executor.setPlainProcess(process);}log.info("{} check if the code is started {}!", requestId, process.isAlive());} catch (IOException e) {log.error("{} start the process {} failed!,error:{}", requestId, command, e);return false;}
其中command就是“python3 test.py”的启动python进程的语句。
停止进程
Field f = process.getClass().getDeclaredField("pid");
f.setAccessible(true);
long pid = f.getLong(process) + 1;
log.info("{} kill process pid {} start", requestId, pid);
process.destroy();
这里不需看细节,其实就是将对应的process对象先进行了存储,之后在主动停止时进行了一次调用。
其实其中的pid+1已经一定程度暴露了信息,因为我们发现真正的python进程号总是与process对象拿到的差1。
例如,我们从process拿到的pid为307,然python的进程号是308
效果
执行完process.destroy()后,对应的307进程退出,但是被拉起的308号python进程仍旧在系统中好好的存在。
问题思考
1、process作为java的进程抽象类,其真正作用是在java进程中再启动一个子的java进程;这个停止动作也只能作用到这个主进程;
2、其中的python进程比启动的子进程大1,因此可以从这个逻辑出发,在java停止掉process时,再发送一个系统调用的停止信号。
最后实现如下
public static void killPlainProcess(Process process, String requestId) throws Exception {Field f = process.getClass().getDeclaredField("pid");f.setAccessible(true);long pid = f.getLong(process) + 1;log.info("{} kill process pid {} start", requestId, pid);killChildProcess(pid);process.destroy();log.info("{} kill process pid {} finished ", requestId, pid);
}/*** mind here, the process usd for call the kill should be clear too!!** @param pidNum*/
private static void killChildProcess(long pidNum) throws Exception {String cmd = "kill -15 " + pidNum;try {Process killProcess = null;killProcess = Runtime.getRuntime().exec(cmd);killProcess.waitFor();TimeUnit.MILLISECONDS.sleep(100);killProcess.destroy();} catch (IOException | InterruptedException e) {throw e;}
}
注意点:在又启动了一个process来执行kill -15信号后,需要注意将自己也执行killProcess.destroy();做好资源清理。
但是发现多次执行后,存在不稳定情况,会导致主进程挂掉。
正确拉起python进程的实现
#### 启动进程
ProcessBuilder builder = new ProcessBuilder("Python", command);
TaskExecutor executor = privpyClient.getTaskExecutor(requestId);
builder.redirectErrorStream(true);
log.info("{} enter running the code: {}", requestId, command);
Process process = null;
try {process = builder.start();if (Objects.nonNull(executor)) {executor.setPlainProcess(process);}log.info("{} check if the code is started {}!", requestId, process.isAlive());
} catch (IOException e) {log.error("{} start the process {} failed!,error:{}", requestId, command, e);return false;
}
其中command就是“test.py”。
更多推荐
java采用Process.destroy无法停止子进程
发布评论