coreshift_core/
process.rs1use crate::CoreError;
11use crate::error::syscall_ret;
12
13pub enum ForkResult {
15 Parent(i32),
17 Child,
19}
20
21pub unsafe fn fork() -> Result<ForkResult, CoreError> {
28 let pid = unsafe { libc::fork() };
29 if pid < 0 {
30 return Err(CoreError::sys(
31 std::io::Error::last_os_error().raw_os_error().unwrap_or(-1),
32 "fork",
33 ));
34 }
35 if pid == 0 {
36 Ok(ForkResult::Child)
37 } else {
38 Ok(ForkResult::Parent(pid))
39 }
40}
41
42pub fn setsid() -> Result<(), CoreError> {
44 let ret = unsafe { libc::setsid() };
45 if ret < 0 {
46 return Err(CoreError::sys(
47 std::io::Error::last_os_error().raw_os_error().unwrap_or(-1),
48 "setsid",
49 ));
50 }
51 Ok(())
52}
53
54pub fn setpgid(pid: i32, pgid: i32) -> Result<(), CoreError> {
56 syscall_ret(unsafe { libc::setpgid(pid, pgid) }, "setpgid")
57}
58
59pub unsafe fn redirect_stdio_to_devnull() -> Result<(), CoreError> {
64 let fd = unsafe {
65 libc::open(b"/dev/null\0".as_ptr() as *const libc::c_char,
66 libc::O_RDWR)
67 };
68 if fd < 0 {
69 return Err(CoreError::sys(
70 std::io::Error::last_os_error().raw_os_error().unwrap_or(-1),
71 "open:/dev/null",
72 ));
73 }
74 unsafe {
75 libc::dup2(fd, 0);
76 libc::dup2(fd, 1);
77 libc::dup2(fd, 2);
78 if fd > 2 { libc::close(fd); }
79 }
80 Ok(())
81}
82
83pub fn set_pdeathsig(sig: i32) -> Result<(), CoreError> {
85 syscall_ret(
86 unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, sig as libc::c_ulong, 0, 0, 0) },
87 "prctl:PR_SET_PDEATHSIG",
88 )
89}
90
91pub unsafe fn redirect_fd_to(src_fd: i32, dst_fd: i32) {
98 unsafe {
99 libc::dup2(src_fd, dst_fd);
100 libc::close(src_fd);
101 }
102}
103
104pub fn getuid() -> u32 { unsafe { libc::getuid() } }
105pub fn getgid() -> u32 { unsafe { libc::getgid() } }
106
107pub fn setuid(uid: u32) -> Result<(), CoreError> {
111 syscall_ret(
112 unsafe { libc::setresuid(uid, uid, uid) },
113 "setresuid",
114 )
115}
116
117pub fn setgid(gid: u32) -> Result<(), CoreError> {
121 syscall_ret(
122 unsafe { libc::setresgid(gid, gid, gid) },
123 "setresgid",
124 )
125}
126
127pub fn close_fds_from(start: i32) {
131 for fd in start..1024 {
132 unsafe { libc::close(fd) };
133 }
134}