Java Runtime.getRuntime (). exec (command)에 대한 불완전한 출력
Oct 28 2020
Jenkins 터미널과 같은 앱을 만들고 싶습니다.
그리고 Java Runtime.getRuntime().exec(command)를 사용 하여 명령을 실행하고 출력이 불완전하다는 것을 확인합니다.
textshell.sh :
# textshell.sh
echo "wwwwwww";
sleep 2
ls
예 : Mac 터미널에서 textshell.sh를 실행하면 다음과 같이 sh -x testshell.sh 출력됩니다.
+ echo wwwwwww
wwwwwww
+ sleep 2
+ ls
testshell.sh
하지만 java 실행하면 Java Runtime.getRuntime().exec("sh -x testshell.sh") 다음과 같이 출력됩니다.
wwwwwww
testshell.sh
쉘 인수 -x는 쓸모없는 것 같습니다
어떻게 고칠 수 있습니까?
답변
1 DuncG Oct 28 2020 at 13:35
@Joachim Sauer가 지적했듯이 STDERR을 읽지 않으므로 출력에서 출력되는 에코 라인을 놓치십시오 set -x. 에 액세스하려면 코드를 조정하십시오 process.getErrorStream().
또는 ProcessBuilder출력과 병합 된 오류 스트림을 읽으려면로 전환 할 수 있습니다 .
String[]cmd = new String[]{"sh", "-x", "testshell.sh"}
ProcessBuilder pb = new ProcessBuilder(cmd);
// THIS MERGES STDERR>STDOUT:
pb.redirectErrorStream(true);
// EITHER send all output to a file here:
Path stdout = Path.of("mergedio.txt");
pb.redirectOutput(stdout.toFile());
Process p = pb.start();
// OR consume your STDOUT p.getInputStream() here as before:
int rc = p.waitFor();
System.out.println("STDOUT: \""+Files.readString(stdout)+'"');