wait.cpp 2.1 KB

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