xref: /plan9/sys/src/ape/lib/ap/plan9/wait.c (revision 9a747e4fd48b9f4522c70c07e8f882a15030f964)
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 		}else{
36 			wpid = w->pid;
37 			if(pid>0 && wpid!=pid){
38 				free(w);
39 				continue;
40 			}
41 			n = wpid;
42 			if(stat_loc){
43 				r = 0;
44 				t = 0;
45 				if(w->msg[0]){
46 					/* message is 'prog pid:string' */
47 					bp = w->msg;
48 					while(*bp){
49 						if(*bp++ == ':')
50 							break;
51 					}
52 					if(*bp == 0)
53 						bp = w->msg;
54 					r = strtol(bp, &ep, 10);
55 					if(*ep == 0){
56 						if(r < 0 || r >= 256)
57 							r = 1;
58 					}else{
59 						t = _stringsig(bp);
60 						if(t == 0)
61 							r = 1;
62 					}
63 				}
64 				*stat_loc = (r << 8) | t;
65 			}
66 			free(w);
67 		}
68 	}
69 	return n;
70 }
71 
72