shell脚本方式
一、判断进程是否挂掉
#!/bin/bash
ps -eaf | grep BCS.out | grep -v grep
if [ $? -ne 0 ]; then
echo "没有运行"
else
echo "正在运行"
fi
二、判断进程是否挂掉,挂掉重启
#!/bin/bash
while true; do
ps -eaf | grep BCS.out | grep -v grep
if [ $? -ne 0 ]; then
echo "没有运行"
nohup /home/kali/www/config/shell/BCS.out >/dev/null 2>&1 &
else
echo "正在运行"
fi
sleep 20
done
java代码方式
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
class Test {
public static void main(String[] args) {
if (!findProcess()) {
start();
}
}
public static boolean findProcess() {
BufferedReader bufferedReader = null;
try {
String procname = "BCS.out";
String[] cmd = new String[]{"bash", "-c", "ps -eaf | grep " + procname + " | grep -v grep"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process process = pb.start();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("BCS")) {
System.out.println(line);
return true;
}
}
int rc = process.waitFor();
if (rc != 0) {
throw new RuntimeException("Failed rc=" + rc + " cmd=" + Arrays.toString(cmd));
}
} catch (Exception e) {
return false;
}
return true;
}
public static void start() {
try {
Runtime.getRuntime().exec("nohup /home/kali/www/config/shell/BCS.out >/dev/null 2>&1 &");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}