简体   繁体   English

在Java中执行Linux命令

[英]Executing Linux Command in Java

I'm trying to execute the following Command in Java in order to kill the spawned process of bash script which is executed through java : 我试图在Java中执行以下命令,以终止通过java执行的bash脚本的生成过程:

kill $(pgrep -P $(pgrep -P 5537)) 

I'm using apache Commons Exec Commandline to build the Command but it's no different to using ProcessBuilder here. 我正在使用apache Commons Exec命令行来构建命令,但是与在这里使用ProcessBuilder没什么不同。 So here is what I have so far: 所以这是我到目前为止所拥有的:

CommandLine cmdLine = new CommandLine("bash");
cmdLine.addArgument("-c");
cmdLine.addArgument("kill $(pgrep -P $(pgrep -P "+pid+"))");

I get the error 我得到错误

bash: $'kill 7940\n7941\n7942\n7943': Command not found.

Normally I would now try to get the newlines out of the Command but it also doesn't work to kill just a single process because then I get the error : 通常我现在会尝试从Command中删除换行符,但是它也无法杀死一个进程,因为这样我会得到以下错误:

bash: kill 7980: Command not found.

One the one hand I need to use bash to use the variables and on the other hand I can't use it because kill can't be executed with it... 一方面我需要使用bash来使用变量,另一方面我不能使用它,因为kill不能用它执行。

firstly kill -9 pidnumber 首先kill -9 pidnumber

Why would you need the bash variables? 为什么需要bash变量? when java gives you strings to store variables? java何时给您字符串来存储变量?

Thirdly why not try System.Runtime.getRuntime().exec() ? 第三,为什么不尝试System.Runtime.getRuntime().exec()呢?

Also do you have permissions to kill the task? 您还具有杀死该任务的权限吗? tried sudo kill -9 pid ? 尝试过sudo kill -9 pid吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM