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