1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.exec.issues;
19
20 import java.io.ByteArrayOutputStream;
21 import java.io.PipedInputStream;
22 import java.io.PipedOutputStream;
23 import java.time.Duration;
24
25 import org.apache.commons.exec.CommandLine;
26 import org.apache.commons.exec.DefaultExecuteResultHandler;
27 import org.apache.commons.exec.DefaultExecutor;
28 import org.apache.commons.exec.Executor;
29 import org.apache.commons.exec.PumpStreamHandler;
30 import org.junit.jupiter.api.Test;
31 import org.junit.jupiter.api.condition.DisabledOnOs;
32
33
34
35
36 public class Exec49Test {
37
38 private static final Duration WAIT = Duration.ofSeconds(10);
39 private final Executor exec = DefaultExecutor.builder().get();
40
41
42
43
44
45
46
47 @Test
48 @DisabledOnOs(org.junit.jupiter.api.condition.OS.WINDOWS)
49 public void testExec49_1() throws Exception {
50 final CommandLine cl = CommandLine.parse("/bin/ls");
51 cl.addArgument("/opt");
52
53 try (PipedOutputStream pipedOutputStream = new PipedOutputStream()) {
54 final PumpStreamHandler psh = new PumpStreamHandler(pipedOutputStream);
55 exec.setStreamHandler(psh);
56
57 System.out.println("Preparing to execute process - commandLine=" + cl.toString());
58 final DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
59 exec.execute(cl, handler);
60 System.out.println("Process spun off successfully - process=" + cl.getExecutable());
61 try (PipedInputStream pis = new PipedInputStream(pipedOutputStream)) {
62 while (pis.read() >= 0) {
63
64
65 }
66 }
67 handler.waitFor(WAIT);
68 handler.getExitValue();
69 }
70 }
71
72
73
74
75
76
77
78 @Test
79 @DisabledOnOs(org.junit.jupiter.api.condition.OS.WINDOWS)
80 public void testExec49_2() throws Exception {
81 final CommandLine cl = CommandLine.parse("/bin/ls");
82 cl.addArgument("/opt");
83
84 try (PipedOutputStream pipedOutputStream = new PipedOutputStream()) {
85 final PumpStreamHandler psh = new PumpStreamHandler(pipedOutputStream, new ByteArrayOutputStream());
86 exec.setStreamHandler(psh);
87
88 System.out.println("Preparing to execute process - commandLine=" + cl.toString());
89 final DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
90 exec.execute(cl, handler);
91 System.out.println("Process spun off successfully - process=" + cl.getExecutable());
92 try (PipedInputStream pis = new PipedInputStream(pipedOutputStream)) {
93 while (pis.read() >= 0) {
94
95
96 }
97 }
98 handler.waitFor(WAIT);
99 handler.getExitValue();
100 }
101 }
102
103 }