wait.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <assert.h>
  7. #include <errno.h>
  8. #include <sys/wait.h>
  9. #include <syscall.h>
  10. #include <unistd.h>
  11. extern "C" {
  12. pid_t wait(int* wstatus)
  13. {
  14. return waitpid(-1, wstatus, 0);
  15. }
  16. pid_t waitpid(pid_t waitee, int* wstatus, int options)
  17. {
  18. siginfo_t siginfo;
  19. idtype_t idtype;
  20. id_t id;
  21. if (waitee < -1) {
  22. idtype = P_PGID;
  23. id = -waitee;
  24. } else if (waitee == -1) {
  25. idtype = P_ALL;
  26. id = 0;
  27. } else if (waitee == 0) {
  28. idtype = P_PGID;
  29. id = getgid();
  30. } else {
  31. idtype = P_PID;
  32. id = waitee;
  33. }
  34. // To be able to detect if a child was found when WNOHANG is set,
  35. // we need to clear si_pid, which will only be set if it was found.
  36. siginfo.si_pid = 0;
  37. int rc = waitid(idtype, id, &siginfo, options | WEXITED);
  38. if (rc < 0)
  39. return rc;
  40. if (wstatus) {
  41. if ((options & WNOHANG) && siginfo.si_pid == 0) {
  42. // No child in a waitable state was found. All other fields
  43. // in siginfo are undefined
  44. *wstatus = 0;
  45. return 0;
  46. }
  47. switch (siginfo.si_code) {
  48. case CLD_EXITED:
  49. *wstatus = siginfo.si_status << 8;
  50. break;
  51. case CLD_KILLED:
  52. *wstatus = siginfo.si_status;
  53. break;
  54. case CLD_STOPPED:
  55. *wstatus = siginfo.si_status << 8 | 0x7f;
  56. break;
  57. case CLD_CONTINUED:
  58. *wstatus = 0xffff;
  59. return 0; // return 0 if running
  60. default:
  61. VERIFY_NOT_REACHED();
  62. }
  63. }
  64. return siginfo.si_pid;
  65. }
  66. int waitid(idtype_t idtype, id_t id, siginfo_t* infop, int options)
  67. {
  68. Syscall::SC_waitid_params params { idtype, id, infop, options };
  69. int rc = syscall(SC_waitid, &params);
  70. __RETURN_WITH_ERRNO(rc, rc, -1);
  71. }
  72. }