java process call

Edit

방법

http://blog.art-of-coding.eu/executing-operating-system-commands-from-java/

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")를 실행시키는 코드로 바꾸어보면, 이 호출은 영원히 끝나지 않게 됩니다.

: : javaworld에 올라온 고전이자 최고의 글

참고할만한 구현체

부모 프로세스의 메모리 복제

외부 프로그램을 실행할 때 JVM에서는 무슨 일이?

Apache Exec

http://commons.apache.org/exec

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