From 7371cbcab030e93260ae356546bdb93d9d28a377 Mon Sep 17 00:00:00 2001 From: Jeremy Soller Date: Thu, 19 Sep 2024 14:59:04 -0600 Subject: [PATCH] unistd: implement daemon function --- src/header/unistd/mod.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/header/unistd/mod.rs b/src/header/unistd/mod.rs index c5fd92a9ae..646d350b99 100644 --- a/src/header/unistd/mod.rs +++ b/src/header/unistd/mod.rs @@ -131,6 +131,35 @@ pub unsafe extern "C" fn crypt(key: *const c_char, salt: *const c_char) -> *mut crypt_r(key, salt, &mut data as *mut _) } +#[no_mangle] +pub extern "C" fn daemon(nochdir: c_int, noclose: c_int) -> c_int { + if nochdir == 0 { + if Sys::chdir(c_str!("/")) < 0 { return -1; } + } + + if noclose == 0 { + let fd = Sys::open(c_str!("/dev/null"), fcntl::O_RDWR, 0).or_minus_one_errno(); + if fd < 0 { return -1; } + if dup2(fd, 0) < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0 { + close(fd); + return -1; + } + if fd > 2 { + close(fd); + } + } + + match fork() { + 0 => {}, + -1 => return -1, + _ => _exit(0), + } + + if setsid() < 0 { return -1; } + + 0 +} + #[no_mangle] pub extern "C" fn dup(fildes: c_int) -> c_int { Sys::dup(fildes)