Austin Schuh | 9049e20 | 2022-02-20 17:34:16 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Implements signal handling (ctrl-c) for OSQP. |
| 3 | * |
| 4 | * Under Windows, we use SetConsoleCtrlHandler. |
| 5 | * Under Unix systems, we use sigaction. |
| 6 | * For Mex files, we use utSetInterruptEnabled/utIsInterruptPending. |
| 7 | * |
| 8 | */ |
| 9 | |
| 10 | #include "ctrlc.h" |
| 11 | |
| 12 | #if defined MATLAB |
| 13 | |
| 14 | static int istate; |
| 15 | |
| 16 | void osqp_start_interrupt_listener(void) { |
| 17 | istate = utSetInterruptEnabled(1); |
| 18 | } |
| 19 | |
| 20 | void osqp_end_interrupt_listener(void) { |
| 21 | utSetInterruptEnabled(istate); |
| 22 | } |
| 23 | |
| 24 | int osqp_is_interrupted(void) { |
| 25 | return utIsInterruptPending(); |
| 26 | } |
| 27 | |
| 28 | #elif defined IS_WINDOWS |
| 29 | |
| 30 | static int int_detected; |
| 31 | static BOOL WINAPI handle_ctrlc(DWORD dwCtrlType) { |
| 32 | if (dwCtrlType != CTRL_C_EVENT) return FALSE; |
| 33 | |
| 34 | int_detected = 1; |
| 35 | return TRUE; |
| 36 | } |
| 37 | |
| 38 | void osqp_start_interrupt_listener(void) { |
| 39 | int_detected = 0; |
| 40 | SetConsoleCtrlHandler(handle_ctrlc, TRUE); |
| 41 | } |
| 42 | |
| 43 | void osqp_end_interrupt_listener(void) { |
| 44 | SetConsoleCtrlHandler(handle_ctrlc, FALSE); |
| 45 | } |
| 46 | |
| 47 | int osqp_is_interrupted(void) { |
| 48 | return int_detected; |
| 49 | } |
| 50 | |
| 51 | #else /* Unix */ |
| 52 | |
| 53 | # include <signal.h> |
| 54 | static int int_detected; |
| 55 | struct sigaction oact; |
| 56 | static void handle_ctrlc(int dummy) { |
| 57 | int_detected = dummy ? dummy : -1; |
| 58 | } |
| 59 | |
| 60 | void osqp_start_interrupt_listener(void) { |
| 61 | struct sigaction act; |
| 62 | |
| 63 | int_detected = 0; |
| 64 | act.sa_flags = 0; |
| 65 | sigemptyset(&act.sa_mask); |
| 66 | act.sa_handler = handle_ctrlc; |
| 67 | sigaction(SIGINT, &act, &oact); |
| 68 | } |
| 69 | |
| 70 | void osqp_end_interrupt_listener(void) { |
| 71 | struct sigaction act; |
| 72 | |
| 73 | sigaction(SIGINT, &oact, &act); |
| 74 | } |
| 75 | |
| 76 | int osqp_is_interrupted(void) { |
| 77 | return int_detected; |
| 78 | } |
| 79 | |
| 80 | #endif /* END IF IS_MATLAB / WINDOWS */ |