shithub: mc

ref: 7d590b64d3ad57239c8835b2fd1a0d2db2b2981a
dir: /libstd/spork.myr/

View raw version
use sys

use "die.use"
use "execvp.use"
use "fmt.use"
use "syswrap.use"

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

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

	/* open up pipes */
	err = pipe(&infds)
	if err != 0
		fatal(1, "Could not create pipes: err %l\n", -err)
	;;
	err = pipe(&outfds)
	if err != 0
		fatal(1, "Could not create pipes: err %l\n", -err)
	;;

	pid = sporkfd(cmd, infds[0] castto(fd), outfds[1] castto(fd))
	/* close unused fd ends */
	close(infds[0]);
	close(outfds[1]);
	-> (pid, infds[1], outfds[0])
}

const sporkfd = {cmd, infd, outfd
	var pid

	pid = fork()
	/* error  */
	if pid == -1
		fatal(1, "Could not fork to start slave\n")
	/* child */
	elif pid == 0
		/* stdin/stdout for our communication. */
		if sys.dup2(infd castto(sys.fd), 0) != 0
			fatal(1, "unable to set stdin\n")
		;;
		if sys.dup2(outfd castto(sys.fd), 1) != 1
			fatal(1, "unable to set stdout\n")
		;;
		close(infd)
		close(outfd)
		if execvp(cmd[0], cmd) < 0
			fatal(1, "failed to exec %s\n")
		;;
	/* parent */
	else
		-> pid castto(pid)
	;;
}