코딩 관련/Java
[JAVA] linux Shell 명령어 실행
메리짱123
2021. 3. 25. 16:02
반응형
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello, World!");
String s;
Process p;
try {
//이 변수에 명령어를 넣어주면 된다.
String[] cmd = {"/bin/sh","-c","ps -ef | grep tomcat"};
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println(s);
p.waitFor();
System.out.println("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {
}
}
}
실행할 명령어를 String[] 타입이 아니라
String cmd = "ls -al";
처럼 String 으로도 넣을 수 있는데...
명령어에 | 파이프가 들어가는 경우엔... 실행이 안 되었다..
그래서 찾아본 결과.. String[] 을 이용하면 된다고 해서 해보니.. 됐음..
String[] cmd = {"/bin/sh","-c","ps -ef | grep tomcat"};
- /bin/sh -c : 그 뒤에 오는 문자열을 실행하라는 의미
- 파이프가 들어가는 명령어 실행 관련하여 참조한 링크
How to make pipes work with Runtime.exec()?
Consider the following code: String commandf = "ls /etc | grep release"; try { // Execute the command and wait for it to complete Process child = Runtime.getRuntime().exec(commandf); ...
stackoverflow.com
반응형