| 34 | }; |
| 35 | |
| 36 | static run_proc_result run_process( |
| 37 | const std::vector<std::string> & args, |
| 38 | size_t max_output, |
| 39 | int timeout_secs) { |
| 40 | run_proc_result res; |
| 41 | |
| 42 | subprocess_s proc; |
| 43 | auto argv = to_cstr_vec(args); |
| 44 | |
| 45 | int options = subprocess_option_no_window |
| 46 | | subprocess_option_combined_stdout_stderr |
| 47 | | subprocess_option_inherit_environment |
| 48 | | subprocess_option_search_user_path; |
| 49 | |
| 50 | if (subprocess_create(argv.data(), options, &proc) != 0) { |
| 51 | res.output = "failed to spawn process"; |
| 52 | return res; |
| 53 | } |
| 54 | |
| 55 | std::atomic<bool> done{false}; |
| 56 | std::atomic<bool> timed_out{false}; |
| 57 | |
| 58 | std::thread timeout_thread([&]() { |
| 59 | auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_secs); |
| 60 | while (!done.load()) { |
| 61 | if (std::chrono::steady_clock::now() >= deadline) { |
| 62 | timed_out.store(true); |
| 63 | subprocess_terminate(&proc); |
| 64 | return; |
| 65 | } |
| 66 | std::this_thread::sleep_for(std::chrono::milliseconds(100)); |
| 67 | } |
| 68 | }); |
| 69 | |
| 70 | FILE * f = subprocess_stdout(&proc); |
| 71 | std::string output; |
| 72 | bool truncated = false; |
| 73 | if (f) { |
| 74 | char buf[4096]; |
| 75 | while (fgets(buf, sizeof(buf), f) != nullptr) { |
| 76 | if (!truncated) { |
| 77 | size_t len = strlen(buf); |
| 78 | if (output.size() + len <= max_output) { |
| 79 | output.append(buf, len); |
| 80 | } else { |
| 81 | output.append(buf, max_output - output.size()); |
| 82 | truncated = true; |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | done.store(true); |
| 89 | if (timeout_thread.joinable()) { |
| 90 | timeout_thread.join(); |
| 91 | } |
| 92 | |
| 93 | subprocess_join(&proc, &res.exit_code); |