Lolly 1.4.27
Loading...
Searching...
No Matches
subprocess.cpp
Go to the documentation of this file.
1
2/******************************************************************************
3 * MODULE : subprocess.cpp
4 * DESCRIPTION: subprocess related routines
5 * COPYRIGHT : (C) 2023 Darcy Shen
6 *******************************************************************************
7 * This software falls under the GNU general public license version 3 or later.
8 * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
9 * in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.
10 ******************************************************************************/
11
12#include <errno.h>
13
14#if defined(OS_MACOS) || defined(OS_LINUX)
15#include <wordexp.h>
16#endif
17
19#include "tbox/tbox.h"
20
21namespace lolly {
22namespace system {
23
24#ifdef OS_WASM
25int
26call (string cmd) {
27 return -1;
28}
29#else
30int
31call (string cmd) {
35
36#if defined(OS_MINGW) || defined(OS_WIN)
37 return (int) tb_process_run_cmd (cmd_c, &attr);
38#else
39 wordexp_t p;
40 int ret= wordexp (cmd_c, &p, 0);
41 if (ret != 0) {
42 return ret;
43 }
44 if (p.we_wordc == 0) {
45 wordfree (&p);
46 return EINVAL;
47 }
48 ret= (int) tb_process_run (p.we_wordv[0], (tb_char_t const**) p.we_wordv,
49 &attr);
50 wordfree (&p);
51 return ret;
52#endif
53}
54#endif
55
56int
57check_output (string s, string& result, bool stderr_only, int64_t timeout) {
58 tb_long_t status= -1;
59 // init pipe files
60 tb_pipe_file_ref_t file[2]= {0};
61 if (!tb_pipe_file_init_pair (file, tb_null, 0)) {
62 return status;
63 }
64
65 // init process
66 c_string cmd_ (s);
69 if (stderr_only) {
70 attr.err.pipe= file[1];
72 }
73 else {
74 attr.out.pipe= file[1];
76 }
78 if (process) {
79 // read pipe data
80 tb_size_t read= 0;
81 // TODO: should be a config here
82 tb_byte_t data[8192]= {0};
83 tb_size_t size = sizeof (data);
84 tb_bool_t wait = tb_false;
85 while (read < size) {
86 tb_long_t real= tb_pipe_file_read (file[0], data + read, size - read);
87 if (real > 0) {
88 read+= real;
89 wait= tb_false;
90 }
91 else if (!real && !wait) {
92 tb_long_t ok = 0;
93 int retry= 25;
94 if (read > 0) {
95 retry= 2;
96 }
97 while (retry > 0 && (ok == 0)) {
99 retry= retry - 1;
100 }
101 tb_check_break (ok > 0);
102 wait= tb_true;
103 }
104 else break;
105 }
106
107 result= as_string ((tb_char_t*) data);
108
109 // wait process
110 tb_process_wait (process, &status, timeout);
111
112 // exit process
114 }
115
116 // exit pipe files
117 tb_pipe_file_exit (file[0]);
118 tb_pipe_file_exit (file[1]);
119 return status;
120}
121
122} // namespace system
123} // namespace lolly
bool read(string s, int &i, const char *test)
Definition analyze.cpp:589
The list class represents a linked list.
Definition list.hpp:48
int call(string cmd)
int check_output(string s, string &result, bool stderr_only, int64_t timeout)
string as_string(int16_t i)
Definition string.cpp:310