一個關於Java執行外部shell命令的疑問筆記

Java 中可以通過 Runtime.getRuntime() 來執行外部命令

在實際中可以用來執行shell 命令一般代碼如下

  1. shell 文件(簡化)
#!/bin/bash

echo "我是shell命令裏輸出的"
  1. Java方法代碼
private String exec(String cmd) throws IOException, InterruptedException {
	String result;
	Process process = Runtime.getRuntime().exec(cmd);
	InputStream is;
	int wait = process.waitFor();
	if (wait == 0) {
		is = process.getInputStream();
	} else {
		is = process.getErrorStream();
	}
	result = IoUtil.read(is, CharsetUtil.CHARSET_UTF_8);
	is.close();
	process.destroy();
	if (StrUtil.isEmpty(result)) {
		result = "沒有返回任何執行信息";
	}
	return result;
}
  1. 調用方法代碼
String msg = exec("/test.sh");
System.out.println(msg);

這樣就會輸出 我是shell命令裏輸出的

一次我在使用shell 命令殺進程時遇到了一個問題

shell 命令代碼大致如下

#!/bin/bash

echo "正在殺死進程"

Tag="systemTestPID"

kill $(pgrep -f ${Tag}) 2>/dev/null

echo "完成"

這樣再使用上面Java 方法調用一直返回:沒有返回任何執行信息 結果調試 waitFor() 方法返回 143 至今還沒有找到原因

這裏請教給位大佬有遇到類似問題或者已經解決此問題的請評論留言,非常感謝

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章