summaryrefslogtreecommitdiffstats
path: root/crates/runner/src/util/unix.rs
blob: 710138ce3a51988154344d03b844e0e257ee7feb (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::{fs::File, os::unix::prelude::*, path::Path};

use nix::{
	fcntl::{self, FcntlArg, FdFlag, OFlag},
	sched,
	unistd::Pid,
};

use common::error::*;

use super::fs;

pub fn set_blocking(fd: RawFd, blocking: bool) -> Result<()> {
	let flags = unsafe {
		OFlag::from_bits_unchecked(fcntl::fcntl(fd, FcntlArg::F_GETFL).context("fcntl(F_GETFL)")?)
	};

	let new_flags = if blocking {
		flags & !OFlag::O_NONBLOCK
	} else {
		flags | OFlag::O_NONBLOCK
	};

	if new_flags != flags {
		fcntl::fcntl(fd, FcntlArg::F_SETFL(new_flags)).context("fcntl(F_SETFL)")?;
	}

	Ok(())
}

pub fn set_cloexec(fd: RawFd, cloexec: bool) -> Result<()> {
	let flags = unsafe {
		FdFlag::from_bits_unchecked(fcntl::fcntl(fd, FcntlArg::F_GETFD).context("fcntl(F_GETFD)")?)
	};

	let new_flags = if cloexec {
		flags | FdFlag::FD_CLOEXEC
	} else {
		flags & !FdFlag::FD_CLOEXEC
	};

	if new_flags != flags {
		fcntl::fcntl(fd, FcntlArg::F_SETFD(new_flags)).context("fcntl(F_SETFD)")?;
	}

	Ok(())
}

pub fn nproc() -> Result<usize> {
	const MAXCPU: usize = sched::CpuSet::count();

	let affinity = sched::sched_getaffinity(Pid::from_raw(0)).context("sched_getaffinity()")?;

	let mut count = 0;

	for cpu in 0..MAXCPU {
		if affinity.is_set(cpu).unwrap() {
			count += 1;
		}
	}

	Ok(count)
}

pub fn lock<P: AsRef<Path>>(path: P, exclusive: bool, blocking: bool) -> Result<File> {
	use fcntl::FlockArg::*;

	if let Some(parent) = path.as_ref().parent() {
		fs::mkdir(parent)?;
	}

	let arg = match (exclusive, blocking) {
		(true, true) => LockExclusive,
		(true, false) => LockExclusiveNonblock,
		(false, true) => LockShared,
		(false, false) => LockSharedNonblock,
	};

	let file = fs::create(path.as_ref())?;
	fcntl::flock(file.as_raw_fd(), arg)
		.with_context(|| format!("flock failed on {:?}", path.as_ref()))?;

	Ok(file)
}