summaryrefslogtreecommitdiffstats
path: root/crates/runner/src/util/clone.rs
blob: 4835b5384a007834af222d7539249d25bac4a3e2 (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
use std::{mem, process};

use nix::{errno, sched, unistd};

#[repr(C)]
#[derive(Debug, Default)]
struct CloneArgs {
	flags: u64,
	pidfd: u64,
	child_tid: u64,
	parent_tid: u64,
	exit_signal: u64,
	stack: u64,
	stack_size: u64,
	tls: u64,
}

pub unsafe fn clone(flags: sched::CloneFlags) -> nix::Result<unistd::ForkResult> {
	let mut args = CloneArgs {
		flags: flags.bits() as u64,
		exit_signal: libc::SIGCHLD as u64,
		..CloneArgs::default()
	};
	let size = mem::size_of_val(&args) as libc::size_t;

	let pid = libc::syscall(libc::SYS_clone3, &mut args, size);
	if pid < 0 {
		Err(errno::Errno::last())
	} else if pid == 0 {
		Ok(unistd::ForkResult::Child)
	} else {
		Ok(unistd::ForkResult::Parent {
			child: unistd::Pid::from_raw(pid as libc::pid_t),
		})
	}
}

pub unsafe fn spawn<T, F>(
	flags: Option<sched::CloneFlags>,
	arg: T,
	f: F,
) -> nix::Result<(unistd::Pid, T)>
where
	F: FnOnce(T),
{
	let res = if let Some(flags) = flags {
		clone(flags)
	} else {
		unistd::fork()
	};
	match res? {
		unistd::ForkResult::Parent { child } => Ok((child, arg)),
		unistd::ForkResult::Child => {
			f(arg);
			process::exit(0)
		}
	}
}