summaryrefslogtreecommitdiff
path: root/lib/std/spork.myr
blob: 81430646d26bb3f4eccb5f567f9dcc232c626583 (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
use "die.use"
use "execvp.use"
use "fmt.use"
use "result.use"
use "syswrap.use"
use "errno.use"

pkg std =
	const spork	: (cmd : byte[:][:]	-> result((pid, fd, fd), errno))
	const sporkfd	: (cmd : byte[:][:], infd : fd, outfd : fd	-> result(pid, errno))
;;

const spork = {cmd
	var infds  :fd[2], outfds : fd[2]
	var err

	/* open up pipes */
	err = pipe(&infds) 
	if err != Enone
		-> `Fail err
	;;
	err = pipe(&outfds)
	if err != Enone
		-> `Fail err
	;;

	match sporkfd(cmd, infds[0] castto(fd), outfds[1] castto(fd))
	| `Ok pid:
		/* close unused fd ends */
		close(infds[0]);
		close(outfds[1]);
		-> `Ok (pid, infds[1], outfds[0])
	| `Fail m:
		-> `Fail m
	;;
}

const sporkfd = {cmd, infd, outfd
	var pid, err

	pid = fork()
	/* error  */
	if pid == -1
		-> `Fail -1
	/* child */
	elif pid == 0
		/* stdin/stdout for our communication. */
		match dup2(infd castto(fd), 0)
		| `Ok _:	/* nothing */
		| `Fail e:	-> `Fail e
		;;
		match dup2(outfd castto(fd), 1)
		| `Ok _:	/* nothing */
		| `Fail e:	-> `Fail e
		;;
		close(infd)
		close(outfd)
		err = execvp(cmd[0], cmd)
		if err != Enone
			-> `Fail err
		;;
		/* if fork succeeds, we never return */
		die("unreachable")
	/* parent */
	else
		-> `Ok pid
	;;
}