Java代码:
package com.spiro;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String command = args[0];
System.out.println("Running command [" + command + "]");
try {
final Process process = Runtime.getRuntime().exec(command);
Thread t1 = new Thread() {
@Override
public void run() {
try {
int exitCode = process.waitFor();
System.out.println("Process exit with code [" + exitCode + "]");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
System.out.println("Waiting 2 seconds.");
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
process.destroy();
System.out.println("Process destroyed");
}
};
t1.start();
t2.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试shell脚本:
#!/bin/sh
echo "abc--1"
sleep 3s
echo "abc--2"
sleep 3s
echo "abc--3"
执行:
java com.spiro.Main "sh /tmp/test.sh"
结果:
Running command [sh /tmp/test.sh]
Waiting 2 seconds.
Process destroyed
Process exit with code [143]
总结
通过 destroy 方法可以kill进程,并可以得到非0得返回码