Google OR-Tools v9.15
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#include "ortools/port/os.h"
22
23#if ORTOOLS_TARGET_OS_SUPPORTS_THREADS
24
25namespace operations_research {
26
27void SigintHandler::Register(const std::function<void()>& f) {
28 handler_ = [this, f]() -> void {
29 const int num_calls = ++num_calls_;
30 if (num_calls < 3) {
31 LOG(INFO)
32 << "^C pressed " << num_calls << " times. "
33 << "Interrupting the solver. Press 3 times to force termination.";
34 if (num_calls == 1) f();
35 } else if (num_calls == 3) {
36 LOG(INFO) << "^C pressed 3 times. Forcing termination.";
37 exit(EXIT_FAILURE);
38 } else {
39 // Another thread is already running exit(), do nothing.
40 }
41 };
42 signal(SIGINT, &SigHandler);
43}
44
45// This method will be called by the system after the SIGINT signal.
46// The parameter is the signal received.
47void SigintHandler::SigHandler(int) { handler_(); }
48
49// Unregister the signal handlers.
50SigintHandler::~SigintHandler() {
51 if (handler_ != nullptr) signal(SIGINT, SIG_DFL);
52}
53
54thread_local std::function<void()> SigintHandler::handler_;
55
56void SigtermHandler::Register(const std::function<void()>& f) {
57 handler_ = [f]() -> void { f(); };
58 signal(SIGTERM, &SigHandler);
59}
60
61// This method will be called by the system after the SIGTERM signal.
62// The parameter is the signal received.
63void SigtermHandler::SigHandler(int) { handler_(); }
64
65// Unregister the signal handlers.
66SigtermHandler::~SigtermHandler() {
67 if (handler_ != nullptr) signal(SIGTERM, SIG_DFL);
68}
69
70thread_local std::function<void()> SigtermHandler::handler_;
71
72} // namespace operations_research
73
74#endif // ORTOOLS_TARGET_OS_SUPPORTS_THREADS
OR-Tools root namespace.