Last active
September 1, 2023 03:11
-
-
Save lrvick/a5eac85999a66e78067a1e47ba93451f to your computer and use it in GitHub Desktop.
rust stdlib signal handling in linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn handle_signals() -> c_int { | |
let mut mask: sigset_t = unsafe { | |
let mut masku = MaybeUninit::<sigset_t>::uninit(); | |
sigemptyset(masku.as_mut_ptr()); | |
masku.assume_init() | |
}; | |
unsafe { sigaddset(&mut mask, SIGINT) }; | |
unsafe { sigaddset(&mut mask, SIGTERM) }; | |
unsafe { sigprocmask(SIG_BLOCK, &mask, ptr::null_mut()) }; | |
let signal = unsafe { sigwaitinfo(&mask, ptr::null_mut()) } as i32; | |
return signal; | |
} | |
fn health_service() { | |
println!("Starting health service"); | |
let listener = TcpListener::bind("0.0.0.0:8080").unwrap(); | |
for stream in listener.incoming() { | |
thread::spawn(move || { | |
let mut stream = stream.unwrap(); | |
let healthy_resp = b"HTTP/1.1 200 OK\r\n\r\n"; | |
let unhealthy_resp = b"HTTP/1.1 503 Service Unavailable\r\n\r\n"; | |
let response = match healthy() { | |
Ok(_) => &healthy_resp[..], | |
_ => &unhealthy_resp[..], | |
}; | |
match stream.write_all(response) { | |
Ok(_) => println!("Health response sent"), | |
Err(e) => println!("Failed sending health response: {}!", e), | |
}; | |
stream.shutdown(Shutdown::Write).unwrap(); | |
}); | |
} | |
} | |
fn main() { | |
println!("Started daemon"); | |
thread::spawn(|| { | |
health_service(); | |
}); | |
let sig_num = handle_signals(); | |
exit(sig_num); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment