shithub: mc

ref: 804ca7d4abe311fb94e02c8e1cd56aad8865a959
dir: /lib/std/execvp.myr/

View raw version
use "alloc"
use "env"
use "errno"
use "fmt"
use "option"
use "strfind"
use "strsplit"
use "syswrap"

pkg std = 
	const execvp	: (cmd : byte[:], args : byte[:][:] -> errno)
	const execvpe	: (cmd : byte[:], args : byte[:][:], env : byte[:][:] -> errno)
;;

const execvp = {cmd, args
	var paths, binpath
	var buf : byte[512]

	match strfind(cmd, "/")
	| `Some _:
		-> execv(cmd, args)
	| `None:
		paths = getpaths()
		for p : paths
			binpath = bfmt(buf[:], "{}/{}", p, cmd)
			execv(binpath, args)
		;;
		slfree(paths)
	;;
	-> -1
}

const execvpe = {cmd, args, env
	var paths, binpath
	var buf : byte[512]

	match strfind(cmd, "/")
	| `Some _:
		-> execve(cmd, args, env)
	| `None:
		paths = getpaths()
		for p : paths
			binpath = bfmt(buf[:], "{}/{}", p, cmd)
			execve(binpath, args, env)
		;;
		slfree(paths)
	;;
	-> -1
}

const getpaths = {
	var path
	match getenv("PATH")
	| `Some p:	path = p
	| `None:	path = "/usr/local/bin:/bin:/usr/bin"
	;;
	-> strsplit(path, ":")
}