【问题标题】:How to kill a Java process started by a script if script was terminated via CTRL + C?如果脚本通过 CTRL + C 终止,如何终止由脚本启动的 Java 进程?
【发布时间】:2012-06-25 06:38:09
【问题描述】:

我有以下script1.sh

#!/bin/bash

trap 'echo "Exit signal detected..."; kill %1' 0 1 2 3 15

./script2.sh & #starts a java app
./script3.sh #starts a different java app

当我执行 CTRL + C 时,它会终止 script1.sh,但由 script2.sh 启动的 Java Swing 应用程序仍然保持打开状态。怎么不杀呢?

【问题讨论】:

标签: java linux bash process


【解决方案1】:

我认为这样的事情可能对你有用。但是,正如@carlspring 提到的,您最好在每个脚本中都有类似的内容,这样您就可以捕获相同的中断并杀死任何丢失的子进程。

随便拿吧

#!/bin/bash

# Store subproccess PIDS
PID1=""
PID2=""

# Call whenever Ctrl-C is invoked
exit_signal(){
    echo "Sending termination signal to childs"
    kill -s SIGINT $PID1 $PID2
    echo "Childs should be terminated now"
    exit 2
}

trap exit_signal SIGINT

# Start proccess and store its PID, so we can kill it latter
proccess1 &
PID1=$!
proccess2 &
PID2=$!

# Keep this process open so we can close it with Ctrl-C
while true; do
    sleep 1
done

【讨论】:

    【解决方案2】:

    好吧,如果您在后台模式下启动脚本(使用&),在调用脚本退出后继续执行是正常行为。您需要通过将echo $$ 存储到文件中来获取第二个脚本的进程ID。然后让各自的脚本有一个stop 命令,当你调用它时,它会杀死这个进程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 2013-04-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      相关资源
      最近更新 更多