|
1 | | -%% SUBPROCESS_RUN run process with optional cwd, env. vars, stdin stream |
| 1 | +%% SUBPROCESS_RUN run process with optional cwd, env. vars, stdin, timeout |
2 | 2 | % |
3 | | -% handle command lines with spaces |
| 3 | +% handles command lines with spaces |
4 | 4 | % input each segment of the command as an element in a string array |
5 | 5 | % this is how python subprocess.run works |
6 | 6 | % |
|
9 | 9 | % * opt.env: environment variable struct to set |
10 | 10 | % * opt.cwd: working directory to use while running command |
11 | 11 | % * opt.stdin: string to pass to subprocess stdin pipe |
| 12 | +% * opt.timeout: time to wait for process to complete before erroring (seconds) |
12 | 13 | %%% Outputs |
13 | | -% * status: 0 is success |
| 14 | +% * status: 0 is generally success. -1 if timeout. Other codes as per the |
| 15 | +% program / command run |
14 | 16 | % * stdout: stdout from process |
15 | 17 | % * stderr: stderr from process |
16 | 18 | % |
|
31 | 33 | opt.env (1,1) struct = struct() |
32 | 34 | opt.cwd (1,1) string = "" |
33 | 35 | opt.stdin (1,1) string = "" |
| 36 | + opt.timeout (1,1) int64 = 0 |
34 | 37 | end |
35 | 38 |
|
36 | 39 | %% process instantiation |
|
67 | 70 | end |
68 | 71 |
|
69 | 72 | %% wait for process to complete |
70 | | -% https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Process.html#waitFor() |
71 | | -status = h.waitFor(); |
| 73 | +% https://docs.oracle.com/en/java/javase/23/docs/api/java.base/java/lang/Process.html#waitFor() |
| 74 | + |
| 75 | +tmsg = ""; |
| 76 | +if opt.timeout > 0 |
| 77 | + % returns true if process completed successfully |
| 78 | + % returns false if process did not complete within timeout |
| 79 | + b = h.waitFor(opt.timeout, java.util.concurrent.TimeUnit.SECONDS); |
| 80 | + if b |
| 81 | + status = 0; |
| 82 | + else |
| 83 | + tmsg = "Subprocess timeout"; |
| 84 | + status = -1; |
| 85 | + end |
| 86 | +else |
| 87 | + % returns 0 if process completed successfully |
| 88 | + status = h.waitFor(); |
| 89 | +end |
72 | 90 |
|
73 | 91 | %% read stdout, stderr pipes |
74 | 92 | stdout = read_stream(h.getInputStream()); |
|
77 | 95 | %% close process |
78 | 96 | h.destroy() |
79 | 97 |
|
| 98 | +stderr = tmsg + stderr; |
| 99 | + |
80 | 100 | if nargout < 2 && strlength(stdout) > 0 |
81 | 101 | disp(stdout) |
82 | 102 | end |
|
0 commit comments