@@ -109,6 +109,10 @@ fn acquire_lock() -> Result<File, CronError> {
109109 . open ( PID_FILE )
110110 . map_err ( CronError :: PidFile ) ?;
111111
112+ // SAFETY: flock() is safe to call here because:
113+ // 1. file.as_raw_fd() returns a valid file descriptor from an open File
114+ // 2. LOCK_EX | LOCK_NB are valid flags for exclusive non-blocking lock
115+ // 3. We check the return value and handle errors appropriately
112116 unsafe {
113117 if libc:: flock ( file. as_raw_fd ( ) , libc:: LOCK_EX | libc:: LOCK_NB ) != 0 {
114118 return Err ( CronError :: AlreadyRunning ) ;
@@ -124,6 +128,12 @@ fn acquire_lock() -> Result<File, CronError> {
124128
125129/// Create new daemon process of crond
126130fn setup ( ) -> i32 {
131+ // SAFETY: These libc calls implement the standard Unix daemon pattern:
132+ // 1. fork() creates child process; parent exits, child continues
133+ // 2. setsid() creates new session, detaches from controlling terminal
134+ // 3. chdir("/") prevents holding directory mounts open
135+ // 4. close(STD*_FILENO) closes inherited file descriptors
136+ // All calls have defined behavior and we check fork() return value.
127137 unsafe {
128138 use libc:: * ;
129139
@@ -153,10 +163,11 @@ extern "C" fn handle_sighup(_: libc::c_int) {
153163
154164/// Handles SIGCHLD signal to reap zombie child processes
155165extern "C" fn handle_sigchld ( _: libc:: c_int ) {
156- unsafe {
157- // Reap all zombie children without blocking
158- while libc:: waitpid ( -1 , std:: ptr:: null_mut ( ) , libc:: WNOHANG ) > 0 { }
159- }
166+ // SAFETY: waitpid() is async-signal-safe per POSIX.
167+ // -1 means wait for any child, WNOHANG returns immediately if no zombie.
168+ // null status pointer is valid when we don't need exit status.
169+ // Loop reaps all available zombies without blocking.
170+ unsafe { while libc:: waitpid ( -1 , std:: ptr:: null_mut ( ) , libc:: WNOHANG ) > 0 { } }
160171}
161172
162173/// Daemon loop
@@ -203,6 +214,9 @@ fn main() -> Result<(), Box<dyn Error>> {
203214 // Acquire PID file lock (keep handle alive for the daemon's lifetime)
204215 let _pid_lock = acquire_lock ( ) ?;
205216
217+ // SAFETY: signal() is safe to call with valid signal numbers and
218+ // extern "C" function handlers. SIGHUP and SIGCHLD are standard signals.
219+ // The handlers are async-signal-safe (only call async-signal-safe functions).
206220 unsafe {
207221 libc:: signal ( libc:: SIGHUP , handle_sighup as usize ) ;
208222 libc:: signal ( libc:: SIGCHLD , handle_sigchld as usize ) ;
@@ -212,5 +226,7 @@ fn main() -> Result<(), Box<dyn Error>> {
212226}
213227
214228fn sleep ( target : u32 ) {
229+ // SAFETY: libc::sleep() is safe with any u32 value; it simply
230+ // suspends execution for the specified number of seconds.
215231 unsafe { libc:: sleep ( target) } ;
216232}
0 commit comments