baseproc-sys.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * This header implements a namespace, bp_sys, which wraps various system calls used by baseproc-service.cc.
  3. *
  4. * When running tests, another header is substituted in place of this one. The substitute provides
  5. * mocks/stubs for the functions, to avoid calling the real functions and thus allow for unit-level testing.
  6. */
  7. #ifndef BPSYS_INCLUDED
  8. #define BPSYS_INCLUDED
  9. #include <cstdlib> // getenv
  10. #include "dasynq.h" // for pipe2
  11. #include <sys/uio.h> // writev
  12. #include <unistd.h>
  13. #include <fcntl.h>
  14. extern char **environ;
  15. namespace bp_sys {
  16. using dasynq::pipe2;
  17. using ::fcntl;
  18. using ::open;
  19. using ::close;
  20. using ::kill;
  21. using ::getpgid;
  22. using ::tcsetpgrp;
  23. using ::getpgrp;
  24. using ::read;
  25. using ::write;
  26. using ::writev;
  27. using std::getenv;
  28. using ::environ;
  29. // Wrapper around a POSIX exit status
  30. class exit_status
  31. {
  32. friend pid_t waitpid(pid_t, exit_status *, int);
  33. int status;
  34. public:
  35. exit_status() noexcept : status(0) { }
  36. explicit exit_status(int status_p) noexcept : status(status_p) { }
  37. bool did_exit() noexcept
  38. {
  39. return WIFEXITED(status);
  40. }
  41. bool did_exit_clean() noexcept
  42. {
  43. // POSIX requires that if the process exited clearly with a status code of 0,
  44. // the exit status value will be 0:
  45. return status == 0;
  46. }
  47. bool was_signalled() noexcept
  48. {
  49. return WIFSIGNALED(status);
  50. }
  51. int get_exit_status() noexcept
  52. {
  53. return WEXITSTATUS(status);
  54. }
  55. int get_term_sig() noexcept
  56. {
  57. return WTERMSIG(status);
  58. }
  59. int as_int() noexcept
  60. {
  61. return status;
  62. }
  63. };
  64. inline pid_t waitpid(pid_t p, exit_status *statusp, int flags)
  65. {
  66. return ::waitpid(p, &statusp->status, flags);
  67. }
  68. }
  69. #endif // BPSYS_INCLUDED