| 351 | out << program; |
| 352 | for (const std::string & arg : args) { |
| 353 | out << ' ' << arg; |
| 354 | } |
| 355 | return out.str(); |
| 356 | } |
| 357 | |
| 358 | int run_process(const std::string & program, const std::vector<std::string> & args) { |
| 359 | #if defined(_WIN32) |
| 360 | std::vector<std::wstring> wide_args; |
| 361 | wide_args.reserve(args.size() + 1); |
| 362 | wide_args.push_back(std::filesystem::path(program).wstring()); |
| 363 | for (const std::string & arg : args) { |
| 364 | wide_args.push_back(std::filesystem::path(arg).wstring()); |
| 365 | } |
| 366 | |
| 367 | std::vector<const wchar_t *> argv; |
| 368 | argv.reserve(wide_args.size() + 1); |
| 369 | for (const std::wstring & arg : wide_args) { |
| 370 | argv.push_back(arg.c_str()); |
| 371 | } |
| 372 | argv.push_back(nullptr); |
| 373 | |
| 374 | const intptr_t rc = _wspawnvp(_P_WAIT, wide_args.front().c_str(), argv.data()); |
| 375 | if (rc == -1) { |
| 376 | throw std::runtime_error( |
| 377 | "failed to launch process: " + format_process_args(program, args) + ": " + std::strerror(errno)); |
| 378 | } |
| 379 | return static_cast<int>(rc); |
| 380 | #else |
| 381 | std::vector<char *> argv; |
| 382 | argv.reserve(args.size() + 2); |
| 383 | argv.push_back(const_cast<char *>(program.c_str())); |
| 384 | for (const std::string & arg : args) { |
| 385 | argv.push_back(const_cast<char *>(arg.c_str())); |
| 386 | } |
| 387 | argv.push_back(nullptr); |
| 388 | |
| 389 | pid_t pid = 0; |
| 390 | const int spawn_rc = posix_spawnp(&pid, program.c_str(), nullptr, nullptr, argv.data(), environ); |
| 391 | if (spawn_rc != 0) { |
| 392 | throw std::runtime_error( |
| 393 | "failed to launch process: " + format_process_args(program, args) + ": " + std::strerror(spawn_rc)); |
| 394 | } |
| 395 | |
| 396 | int status = 0; |
| 397 | while (waitpid(pid, &status, 0) < 0) { |
| 398 | if (errno != EINTR) { |
| 399 | throw std::runtime_error("failed waiting for process: " + program + ": " + std::strerror(errno)); |
| 400 | } |
| 401 | } |
| 402 | if (WIFEXITED(status)) { |
| 403 | return WEXITSTATUS(status); |
| 404 | } |
| 405 | if (WIFSIGNALED(status)) { |
| 406 | return 128 + WTERMSIG(status); |
| 407 | } |
| 408 | throw std::runtime_error("process exited unexpectedly: " + program); |
no test coverage detected