在守护进程的java进程中运行脚本并终止进程

时间:2018-04-18 12:53:10

标签: java shell systemd runtime.exec

我有一个Java程序,它启动一个脚本,它执行一些作业job1并杀死java程序并完成一些其他的job job2。除了一种情况外,它的效果很好 当java程序是systemd守护程序时,kill命令也会杀死守护程序。所以只有job1完成,job2永远不会完成。

如何实施上述方案?

我和不同的人玩过#nohup ......"情景,但从未实现。

以下是文件:

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;

public class Main {

public static void main(String[] args) {
    String jvmName = ManagementFactory.getRuntimeMXBean().getName();
    String pid = jvmName.split("@")[0];
    System.out.println(pid);
    try {
        Process process = Runtime.getRuntime().exec("nohup ./start.sh " + pid + " & > /dev/null 2>&1 &", new String[] {},
                new File("/home/someuser/eclipse-workspace/nohup/"));


        int exitCode = process.waitFor();
        System.out.println(exitCode);
    } catch (IOException | InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

这是shell脚本:

#!/bin/bash
echo 'start ' $(date) >>deneme.txt
echo $1 >>deneme.txt
echo $$ >>deneme.txt
sleep 10
kill -9 $1
sleep 10
echo 'end ' $(date) >>deneme.txt

这是系统定义

[Unit]
Description=Nohup Deneme
After=syslog.target
[Service]
WorkingDirectory=/home/someuser/eclipse-workspace/nohup
SyslogIdentifier=montaigne
ExecStart=/bin/bash -c "java -jar /home/someuser/eclipse-workspace/nohup/deneme.jar"
User=someuser
Type=simple
[Install]
WantedBy=multi-user.target

编辑:

我已阅读https://stackoverflow.com/a/1491689/5236126

当我捕获SIGTERM时,我现在可以处理它了。

#!/bin/bash

job1()
{
  echo 'deneme started'
  echo 'start ' $(date) >>deneme.txt
  echo 'version ' $2 >>deneme.txt
  echo 'process to be killed: ' $1 >>deneme.txt
  echo 'pid: ' $$ >>deneme.txt
  echo 'parent: ' $PPID >>deneme.txt    
}

job2()
{
  echo "Caught Signal " $1 " ... cleaning up." >>deneme.txt
  sleep 4
  echo 'parent after kill: ' $PPID >>deneme.txt
  echo 'end ' $(date) >>deneme.txt
  echo 'deneme stopped'
  exit 1
}


trap job2 15
job1
sleep 5
kill -9 $1 >>deneme.txt
sleep 1
job2 'no-signal'

0 个答案:

没有答案