1 extern crate libc; 2 use libc::{signal, sleep, syscall, SYS_alarm, SIGALRM}; 3 4 extern "C" fn handle_alarm(_: i32) { 5 println!("Alarm ring!"); 6 } 7 8 fn main() { 9 // 设置信号处理函数 10 unsafe { 11 signal(SIGALRM, handle_alarm as usize); 12 } 13 14 //test1: alarm系统调用能否正常运行 15 unsafe { 16 syscall(SYS_alarm, 5); 17 } 18 println!("Alarm set for 5 seconds"); 19 unsafe { 20 sleep(6); 21 } 22 println!("Test 1 complete"); 23 24 //test2:在上一个alarm定时器未完成时重新调用alarm,查看返回值是否为上一个alarm的剩余秒数, 25 //并test第三个alarm定时器能否正常运行 26 27 unsafe { 28 let remaining = syscall(SYS_alarm, 5); 29 println!("Remaining time for previous alarm: {}", remaining); 30 } 31 println!("Alarm set for 5 seconds"); 32 unsafe { 33 let remaining = syscall(SYS_alarm, 3); 34 println!("Remaining time for previous alarm: {}", remaining); 35 } 36 unsafe { 37 sleep(4); 38 } 39 println!("Alarm set for 3 seconds"); 40 41 println!("Test 2 complete"); 42 } 43