2012-06-25 32 views
3

我有以下script1.sh如果通过CTRL + C终止脚本,如何杀死由脚本启动的Java进程?

#!/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,但Java Swing应用程序开始通过script2.sh仍保持开放。它怎么没有杀死它?

+0

[Bash的?我该如何使一个脚本的子进程被终止,当脚本被终止]的可能重复(http://stackoverflow.com/questions/ 7817637/bash-how-do-i-make-sub-processes-of-a-script-be-terminated-when-the-script-is) – Thilo

+0

另外:http://stackoverflow.com/questions/360201/kill -background-process-when-shell-script-exit – Thilo

+0

我试过了两个。如果它正在运行,它们都不会杀死真正的Java应用程序... –

回答

0

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

+1

如果您想捕获ctrl + c,请使用[trap](http://hacktux.com/bash/control/c) – Miquel

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 
相关问题