How to use libc's signal function?

I am trying to use libc::funcs::posix01::signal::signal in order to create a handler to intercept SIGINT and I am not sure how to coerce a function into a sighandler_t. As far as I can tell an &extern "C" fn() {c_handle} cant be turned into a sighandler_t

extern crate libc;
use libc::sighandler_t;
use libc::{c_int, c_void, SIGINT};
use libc::funcs::posix01::signal::signal;

extern fn handler(_: c_int) {}

fn get_handler() -> sighandler_t {
    handler as extern fn(c_int) as *mut c_void as sighandler_t
}

fn main() {
    unsafe { signal(SIGINT, get_handler()); }
}

Note that you have to be really careful what you do inside of a signal handler. It's exceedingly unsafe.

If you need to do anything non-trivial, it might be eaiser to just use the sigwait approach. My crate chan-signal uses that strategy and sends signals over a channel.

2 Likes

Yep, that worked. Thanks!

Thankfully all I really need to do is have some sort of handler to stop the program from crashing. I'm working on a shell and it isn't useful if the shell crashes when control-c is pressed.

Well, in that case you need to either pass it to the program being run or handle it as a text input command, no?