wait.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "lib.h"
  2. #include <stdlib.h>
  3. #include <sys/wait.h>
  4. #include <sys/stat.h>
  5. #include <unistd.h>
  6. #include <errno.h>
  7. #include <stdio.h>
  8. #include "sys9.h"
  9. pid_t
  10. wait(int *stat_loc)
  11. {
  12. return waitpid(-1, stat_loc, 0);
  13. }
  14. pid_t
  15. waitpid(int pid, int *stat_loc, int options)
  16. {
  17. int n, i, wfd, r, t, wpid;
  18. char *bp, *ep, pname[50];
  19. struct stat buf;
  20. Waitmsg *w;
  21. if(options&WNOHANG){
  22. sprintf(pname, "/proc/%d/wait", getpid());
  23. i = stat(pname, &buf);
  24. if(i >=0 && buf.st_size==0)
  25. return 0;
  26. }
  27. n = 0;
  28. while(n==0){
  29. w = _WAIT();
  30. if(w == 0){
  31. _syserrno();
  32. n = -1;
  33. }else{
  34. wpid = w->pid;
  35. if(pid>0 && wpid!=pid){
  36. free(w);
  37. continue;
  38. }
  39. n = wpid;
  40. if(stat_loc){
  41. r = 0;
  42. t = 0;
  43. if(w->msg[0]){
  44. /* message is 'prog pid:string' */
  45. bp = w->msg;
  46. while(*bp){
  47. if(*bp++ == ':')
  48. break;
  49. }
  50. if(*bp == 0)
  51. bp = w->msg;
  52. r = strtol(bp, &ep, 10);
  53. if(*ep == 0){
  54. if(r < 0 || r >= 256)
  55. r = 1;
  56. }else{
  57. t = _stringsig(bp);
  58. if(t == 0)
  59. r = 1;
  60. }
  61. }
  62. *stat_loc = (r << 8) | t;
  63. }
  64. free(w);
  65. }
  66. }
  67. return n;
  68. }