@@ -3,9 +3,14 @@ mod thread_pool;
33
44use chrono:: Utc ;
55use clap:: Parser ;
6+ use ctrlc;
67use log:: { error, info} ;
7- use std:: fs:: { self , metadata , File } ;
8+ use std:: fs:: { self , File } ;
89use std:: path:: PathBuf ;
10+ use std:: sync:: {
11+ atomic:: { AtomicBool , Ordering } ,
12+ Arc ,
13+ } ;
914use std:: thread;
1015use std:: time:: Duration ;
1116
@@ -36,6 +41,16 @@ fn main() -> Result<(), std::io::Error> {
3641 env_logger:: init ( ) ;
3742 let args = Args :: parse ( ) ;
3843
44+ let running = Arc :: new ( AtomicBool :: new ( true ) ) ;
45+ {
46+ let running = Arc :: clone ( & running) ;
47+ ctrlc:: set_handler ( move || {
48+ running. store ( false , Ordering :: SeqCst ) ;
49+ println ! ( "\n Received interruption (Ctrl+C), shutting down gracefully..." ) ;
50+ } )
51+ . expect ( "Error setting up Ctrl+C handler" ) ;
52+ }
53+
3954 let mut has_tasks: bool = true ;
4055 let mut thread_pool: ThreadPool = ThreadPool :: new ( args. jobs ) ;
4156
@@ -58,7 +73,7 @@ fn main() -> Result<(), std::io::Error> {
5873 print ! ( "{thread_pool}" ) ;
5974 }
6075
61- while args. demon || has_tasks {
76+ while ( args. demon || has_tasks) && running . load ( Ordering :: SeqCst ) {
6277 if is_dir {
6378 history_file = backlog_path. join ( "qrun_history.log" ) ;
6479 let mut found_file = false ;
@@ -90,18 +105,15 @@ fn main() -> Result<(), std::io::Error> {
90105
91106 if let Some ( file) = & backlog_file {
92107 if file. exists ( ) {
93- // Read the backlog
94108 let mut tasks = rw_file:: read ( & file) ;
95109
96- while !tasks. is_empty ( ) {
110+ while !tasks. is_empty ( ) && running . load ( Ordering :: SeqCst ) {
97111 while thread_pool. has_one_available ( ) && !tasks. is_empty ( ) {
98112 let thread_id = thread_pool. get_one_available ( ) ;
99113 if let Some ( thread_id) = thread_id {
100114 let task = tasks[ 0 ] . to_string ( ) ;
101115 tasks. remove ( 0 ) ;
102- // println!("{} - {}", thread_id, &task);
103116 rw_file:: append ( & history_file, & task) ?;
104-
105117 thread_pool. exec_task ( thread_id, task, log_file. try_clone ( ) ?) ;
106118 }
107119 }
@@ -115,7 +127,7 @@ fn main() -> Result<(), std::io::Error> {
115127 thread:: sleep ( Duration :: from_secs ( 1 ) ) ;
116128 }
117129
118- while thread_pool. is_ongoing ( ) {
130+ while thread_pool. is_ongoing ( ) && running . load ( Ordering :: SeqCst ) {
119131 if !args. demon {
120132 print ! ( "{thread_pool}" ) ;
121133 }
@@ -125,8 +137,11 @@ fn main() -> Result<(), std::io::Error> {
125137 thread:: sleep ( Duration :: from_secs ( 1 ) ) ;
126138 }
127139
128- // rw_file::write(&file, &tasks)?;
129- fs:: remove_file ( file) ?;
140+ if !tasks. is_empty ( ) {
141+ rw_file:: write ( & file, & tasks) ?;
142+ } else {
143+ fs:: remove_file ( file) ?;
144+ }
130145 has_tasks = false ;
131146 }
132147 }
0 commit comments