is_running.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (c) 2106 Klemens D. Morgenstern
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_PROCESS_DETAIL_POSIX_IS_RUNNING_HPP
  6. #define BOOST_PROCESS_DETAIL_POSIX_IS_RUNNING_HPP
  7. #include <boost/process/detail/config.hpp>
  8. #include <boost/process/detail/posix/child_handle.hpp>
  9. #include <system_error>
  10. #include <sys/wait.h>
  11. namespace boost { namespace process { namespace detail { namespace posix {
  12. // Use the "stopped" state (WIFSTOPPED) to indicate "not terminated".
  13. // This bit arrangement of status codes is not guaranteed by POSIX, but (according to comments in
  14. // the glibc <bits/waitstatus.h> header) is the same across systems in practice.
  15. constexpr int still_active = 0x7F;
  16. static_assert(!WIFEXITED(still_active) && !WIFSIGNALED(still_active), "Internal Error");
  17. inline bool is_running(int code)
  18. {
  19. return !WIFEXITED(code) && !WIFSIGNALED(code);
  20. }
  21. inline bool is_running(const child_handle &p, int & exit_code, std::error_code &ec) noexcept
  22. {
  23. int status;
  24. auto ret = ::waitpid(p.pid, &status, WNOHANG);
  25. if (ret == -1)
  26. {
  27. if (errno != ECHILD) //because it no child is running, than this one isn't either, obviously.
  28. ec = ::boost::process::detail::get_last_error();
  29. return false;
  30. }
  31. else if (ret == 0)
  32. return true;
  33. else
  34. {
  35. ec.clear();
  36. if (!is_running(status))
  37. exit_code = status;
  38. return false;
  39. }
  40. }
  41. inline bool is_running(const child_handle &p, int & exit_code)
  42. {
  43. std::error_code ec;
  44. bool b = is_running(p, exit_code, ec);
  45. boost::process::detail::throw_error(ec, "waitpid(2) failed in is_running");
  46. return b;
  47. }
  48. inline int eval_exit_status(int code)
  49. {
  50. if (WIFEXITED(code))
  51. {
  52. return WEXITSTATUS(code);
  53. }
  54. else if (WIFSIGNALED(code))
  55. {
  56. return WTERMSIG(code);
  57. }
  58. else
  59. {
  60. return code;
  61. }
  62. }
  63. }}}}
  64. #endif