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.OS;
30 import org.apache.commons.exec.PumpStreamHandler;
31 import org.junit.jupiter.api.Test;
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 public void testExec49_1() throws Exception {
49 if (OS.isFamilyUnix()) {
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
79 @Test
80 public void testExec49_2() throws Exception {
81 if (OS.isFamilyUnix()) {
82 final CommandLine cl = CommandLine.parse("/bin/ls");
83 cl.addArgument("/opt");
84
85 try (PipedOutputStream pipedOutputStream = new PipedOutputStream()) {
86 final PumpStreamHandler psh = new PumpStreamHandler(pipedOutputStream, new ByteArrayOutputStream());
87 exec.setStreamHandler(psh);
88
89 System.out.println("Preparing to execute process - commandLine=" + cl.toString());
90 final DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
91 exec.execute(cl, handler);
92 System.out.println("Process spun off successfully - process=" + cl.getExecutable());
93 try (PipedInputStream pis = new PipedInputStream(pipedOutputStream)) {
94 while (pis.read() >= 0) {
95
96
97 }
98 }
99 handler.waitFor(WAIT);
100 handler.getExitValue();
101 }
102 }
103 }
104
105 }