终止由* nix上的ProcessBuilder生成的子进程 [英] Terminate child processes spawned by a ProcessBuilder on *nix
问题描述
我正在从java程序执行shell管道 - 它将类似于
I'm executing a shell pipeline from a java program - it'll be something like
ProcessBuilder builder = new ProcessBuilder(
"sh", "-c", "program1 | program2 | program3");
builder.start();
在某些情况下,可能需要终止此单元。但是
In some cases this unit might need to be terminated. However
process.destroy();
只会销毁sh命令。 pipline中的命令将被孤立并由init进程采用。
Will only destroy the "sh" command. The commands in the pipline will be orphaned and adopted by the init process.
有没有办法轻松终止所有这些子进程 - 或执行如上所述的管道一种使它更容易终止的方法。改变程序1/2/3无法完成。超出linux的可移植性不是问题。
Is there any way to easily terminate all these child processes - or execute a pipeline like the above in a way that makes it easier to terminate them . Altering progam 1/2/3 can't be done. Portability beyond linux is not a issue.
推荐答案
我有两种方法可以做到这一点:
There's two ways I can think to do this:
-
你可以运行一个pkill program1 program2 program3
You could run a pkill program1 program2 program3
你可以编写一个中级程序启动整个bash命令行,这个中间程序会安装一个信号处理程序,当它收到STOP信号时会杀死它自己的孩子。
You could write a intermediate program which launches the whole bash command line, this intermediate program would install a signal handler which kills it's own children when it gets a STOP signal.
这篇关于终止由* nix上的ProcessBuilder生成的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!