aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.posix/exec.cc
blob: 5bdcbf70695ae8435bfb2fccb6eaf09f7533c036 (plain) (blame)
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
/*
 * This source code is released into the public domain.
 */

module;

#include <coroutine>
#include <expected>
#include <format>
#include <string>
#include <utility>

#include <err.h>
#include <fcntl.h>
#include <unistd.h>

extern char **environ;

module nihil.posix;

import nihil.error;
import nihil.monad;

namespace nihil {

fexecv::fexecv(fd &&execfd, argv &&args) noexcept
	: m_execfd(std::move(execfd))
	, m_args(std::move(args))
{
}

auto fexecv::exec(this fexecv &self)
	-> std::expected<void, error>
{
	::fexecve(self.m_execfd.get(), self.m_args.data(), environ);
	return std::unexpected(error("fexecve failed",
				     error(std::errc(errno))));
}
	
fexecv::fexecv(fexecv &&) noexcept = default;
auto fexecv::operator=(this fexecv &, fexecv &&) noexcept -> fexecv& = default;
	
auto execv(std::string_view path, argv &&argv)
	-> std::expected<fexecv, error>
{
	auto file = co_await open(path, O_EXEC)
		.transform_error([&] (error cause) {
			return error(std::format("could not open {}", path),
				     std::move(cause));
		});

	co_return fexecv(std::move(file), std::move(argv));
}

auto execvp(std::string_view file, argv &&argv)
	-> std::expected<fexecv, error>
{
	auto execfd = find_in_path(file);
	if (!execfd)
		return std::unexpected(error(
			std::format("executable not found in path: {}", file)));
	return fexecv(std::move(*execfd), std::move(argv));
}

auto shell(std::string_view const &command)
	-> std::expected<fexecv, error>
{
	return execl("/bin/sh", "sh", "-c", command);
}

} // namespace nihil