3939namespace huggingface_hub {
4040
4141volatile sig_atomic_t stop_download = 0 ;
42- void handle_sigint (int ) { stop_download = 1 ; }
42+ volatile sig_atomic_t has_previous_sigint_handler = 0 ;
43+ struct sigaction previous_sigint_action;
44+
45+ void handle_sigint (int signo) {
46+ stop_download = 1 ;
47+
48+ if (!has_previous_sigint_handler) {
49+ return ;
50+ }
51+
52+ if ((previous_sigint_action.sa_flags & SA_SIGINFO ) != 0 ) {
53+ if (previous_sigint_action.sa_sigaction != nullptr ) {
54+ previous_sigint_action.sa_sigaction (signo, nullptr , nullptr );
55+ }
56+ return ;
57+ }
58+
59+ if (previous_sigint_action.sa_handler != SIG_IGN &&
60+ previous_sigint_action.sa_handler != SIG_DFL &&
61+ previous_sigint_action.sa_handler != nullptr &&
62+ previous_sigint_action.sa_handler != handle_sigint) {
63+ previous_sigint_action.sa_handler (signo);
64+ }
65+ }
66+
67+ class ScopedSigintHandler {
68+ public:
69+ ScopedSigintHandler () : installed_(false ) {
70+ stop_download = 0 ;
71+
72+ struct sigaction action;
73+ sigemptyset (&action.sa_mask );
74+ action.sa_flags = 0 ;
75+ action.sa_handler = handle_sigint;
76+
77+ if (sigaction (SIGINT , &action, &previous_sigint_action) == 0 ) {
78+ has_previous_sigint_handler = 1 ;
79+ installed_ = true ;
80+ } else {
81+ has_previous_sigint_handler = 0 ;
82+ }
83+ }
84+
85+ ~ScopedSigintHandler () {
86+ if (installed_) {
87+ sigaction (SIGINT , &previous_sigint_action, nullptr );
88+ }
89+ has_previous_sigint_handler = 0 ;
90+ }
91+
92+ private:
93+ bool installed_;
94+ };
4395
4496bool log_verbose = false ;
4597
@@ -398,7 +450,7 @@ struct DownloadResult hf_hub_download(const std::string &repo_id,
398450 const std::string &filename,
399451 const std::string &cache_dir,
400452 bool force_download, bool verbose) {
401- signal ( SIGINT , handle_sigint) ;
453+ ScopedSigintHandler scoped_sigint_handler ;
402454 log_verbose = verbose;
403455
404456 struct DownloadResult result;
@@ -570,4 +622,4 @@ struct DownloadResult hf_hub_download_with_shards(const std::string &repo_id,
570622 return hf_hub_download (repo_id, filename, cache_dir, force_download);
571623}
572624
573- } // namespace huggingface_hub
625+ } // namespace huggingface_hub
0 commit comments