1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
#include <u.h>
#include <libc.h>
#include <thread.h>
#include <9pclient.h>
#include "acme.h"
extern int debug;
#define dprint if(debug>1)print
typedef struct Waitreq Waitreq;
struct Waitreq
{
int pid;
Channel *c;
};
/*
* watch the exiting children
*/
Channel *twaitchan; /* chan(Waitreq) */
void
waitthread(void *v)
{
Alt a[3];
Waitmsg *w, **wq;
Waitreq *rq, r;
int i, nrq, nwq;
threadsetname("waitthread");
a[0].c = threadwaitchan();
a[0].v = &w;
a[0].op = CHANRCV;
a[1].c = twaitchan;
a[1].v = &r;
a[1].op = CHANRCV;
a[2].op = CHANEND;
nrq = 0;
nwq = 0;
rq = nil;
wq = nil;
dprint("wait: start\n");
for(;;){
cont2:;
dprint("wait: alt\n");
switch(alt(a)){
case 0:
dprint("wait: pid %d exited\n", w->pid);
for(i=0; i<nrq; i++){
if(rq[i].pid == w->pid){
dprint("wait: match with rq chan %p\n", rq[i].c);
sendp(rq[i].c, w);
rq[i] = rq[--nrq];
goto cont2;
}
}
if(i == nrq){
dprint("wait: queueing waitmsg\n");
wq = erealloc(wq, (nwq+1)*sizeof(wq[0]));
wq[nwq++] = w;
}
break;
case 1:
dprint("wait: req for pid %d chan %p\n", r.pid, r.c);
for(i=0; i<nwq; i++){
if(w->pid == r.pid){
dprint("wait: match with waitmsg\n");
sendp(r.c, w);
wq[i] = wq[--nwq];
goto cont2;
}
}
if(i == nwq){
dprint("wait: queueing req\n");
rq = erealloc(rq, (nrq+1)*sizeof(rq[0]));
rq[nrq] = r;
dprint("wait: queueing req pid %d chan %p\n", rq[nrq].pid, rq[nrq].c);
nrq++;
}
break;
}
}
}
Waitmsg*
twaitfor(int pid)
{
Waitreq r;
Waitmsg *w;
r.pid = pid;
r.c = chancreate(sizeof(Waitmsg*), 1);
send(twaitchan, &r);
w = recvp(r.c);
chanfree(r.c);
return w;
}
int
twait(int pid)
{
int x;
Waitmsg *w;
w = twaitfor(pid);
x = w->msg[0] != 0 ? -1 : 0;
free(w);
return x;
}
void
twaitinit(void)
{
threadwaitchan(); /* allocate it before returning */
twaitchan = chancreate(sizeof(Waitreq), 10);
threadcreate(waitthread, nil, 128*1024);
}
|