Skip to content

Latest commit

 

History

History
133 lines (89 loc) · 5.09 KB

java-process-call.adoc

File metadata and controls

133 lines (89 loc) · 5.09 KB

방법

import java.io.IOException;

import java.io.InputStream;

import org.apache.commons.io.IOUtils;

import org.junit.Test;

public class ShellTest {

String[] command = new String[]{"ls","-al"};
@Test
public void withProcessBuilder() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();
printStream(process);
}
@Test
public void withRunetime() throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
printStream(process);
}
private void printStream(Process process) throws IOException, InterruptedException {
process.waitFor();
InputStream stream = process.getInputStream();
IOUtils.copy(stream, System.out);
IOUtils.closeQuietly(stream);
}

}

무한 대기 문제
public static void main(String[] args) throws IOException, InterruptedException{
       Process pc = Runtime.getRuntime().exec("java");
       InputStream input = pc.getInputStream();
       IOUtils.copy(input, System.out);
       int exitCode = pc.waitFor();
       System.out.println(exitCode);
}

waitFor는 무한대기 될 수도 있다…​

그런데 위의 코드를 Runtime.exec("javac")를 실행시키는 코드로 바꾸어보면, 이 호출은 영원히 끝나지 않게 됩니다.

When Runtime.exec() won’t : : javaworld에 올라온 고전이자 최고의 글

참고할만한 구현체

Apache Exec

<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-exec</artifactId> <version>1.1</version> </dependency>