Google OR-Tools v9.14
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
sigint.cc
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14#include "ortools/util/sigint.h"
15
16#include <csignal>
17#include <cstdlib>
18#include <functional>
19
21
22namespace operations_research {
23
24void SigintHandler::Register(const std::function<void()>& f) {
25 handler_ = [this, f]() -> void {
26 const int num_calls = ++num_calls_;
27 if (num_calls < 3) {
28 LOG(INFO)
29 << "^C pressed " << num_calls << " times. "
30 << "Interrupting the solver. Press 3 times to force termination.";
31 if (num_calls == 1) f();
32 } else if (num_calls == 3) {
33 LOG(INFO) << "^C pressed 3 times. Forcing termination.";
34 exit(EXIT_FAILURE);
35 } else {
36 // Another thread is already running exit(), do nothing.
37 }
38 };
39 signal(SIGINT, &SigHandler);
40}
41
42// This method will be called by the system after the SIGINT signal.
43// The parameter is the signal received.
44void SigintHandler::SigHandler(int) { handler_(); }
45
46// Unregister the signal handlers.
48 if (handler_ != nullptr) signal(SIGINT, SIG_DFL);
49}
50
51thread_local std::function<void()> SigintHandler::handler_;
52
53void SigtermHandler::Register(const std::function<void()>& f) {
54 handler_ = [f]() -> void { f(); };
55 signal(SIGTERM, &SigHandler);
56}
57
58// This method will be called by the system after the SIGTERM signal.
59// The parameter is the signal received.
60void SigtermHandler::SigHandler(int) { handler_(); }
61
62// Unregister the signal handlers.
64 if (handler_ != nullptr) signal(SIGTERM, SIG_DFL);
65}
66
67thread_local std::function<void()> SigtermHandler::handler_;
68
69} // namespace operations_research
~SigintHandler()
Unregister the signal handlers.
Definition sigint.cc:47
void Register(const std::function< void()> &f)
Definition sigint.cc:24
void Register(const std::function< void()> &f)
Definition sigint.cc:53
~SigtermHandler()
Unregister the signal handlers.
Definition sigint.cc:63
In SWIG mode, we don't want anything besides these top-level includes.