summaryrefslogtreecommitdiff
path: root/lib/std/wait+plan9.myr
blob: 2097c008d4393e2ada8ea65e3d272c024054f08b (plain)
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
use sys

use "alloc"
use "chartype"
use "die"
use "extremum"
use "hashfuncs"
use "hasprefix"
use "htab"
use "intparse"
use "option"
use "strsplit"
use "striter"
use "syswrap"
use "utf"
use "sleq"
use "fmt"
use "threadhooks"

pkg std =
	type waitstatus = union
		`Wsuccess
		`Wfailure
		`Wsignalled
		`Waiterror
	;;

	const wait	: (pid : pid -> waitstatus)
	const waitany	: (-> (pid, waitstatus))
;;

var statusmap	: htab(pid, waitstatus)#

const __init__ = {
	statusmap = mkht()
}

const waitany = {
	var buf : byte[512]
	var ret, it

	lock(envlck)
	if htcount(statusmap) == 0
		unlock(envlck)
		match sys.await(buf[:])
		| -1:	-> (-1, `Waiterror)
		| n:	-> parsestatus(buf[:n])
		;;
	else
		it = std.byhtkeyvals(statusmap)
		__iternext__(&it, &ret)
		unlock(envlck)
		-> ret
	;;
}

const wait = {pid
	var buf : byte[512]
	var xpid, status

	lock(envlck)
	match htget(statusmap, pid)
	| `None:
	| `Some st:
		unlock(envlck)
		htdel(statusmap, pid)
		-> st
	;;
	unlock(envlck)

	while true
		match sys.await(buf[:])
		| -1:	-> `Waiterror
		| n:	(xpid, status) = parsestatus(buf[:n])
		;;
		if xpid == pid
			-> status
		else
			lock(envlck)
			htput(statusmap, xpid, status)
			unlock(envlck)
		;;
	;;
	/* impossible */
	-> `Waiterror
}

const parsestatus = {status	-> (pid, waitstatus)
	var st : waitstatus
	var spbuf : byte[:][5]
	var xpid, sp

	sp = bstrsplit(spbuf[:], status, " ")
	if sp.len == 0
		-> (-1, `Wfailure)
	;;

	match intparse(sp[0])
	| `Some pid:
		xpid = pid
		/* exits(nil) => sp[0] either not present or equal to '' */
		if sp.len == 4 || (sp.len == 5 && sleq(sp[4], "''"))
			st = `Wsuccess
		elif sp.len == 5
			st = `Wfailure
		else	/* we have a malformed await message */
			st = `Waiterror
		;;
	| `None:
		xpid = -1
		st = `Waiterror
	;;

	-> (xpid, st)

}