| 1 | // Copyright 2018 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "DolphinQt/QtUtils/SignalDaemon.h" |
| 5 | |
| 6 | #include <sys/socket.h> |
| 7 | #include <unistd.h> |
| 8 | |
| 9 | #include <QSocketNotifier> |
| 10 | |
| 11 | int SignalDaemon::s_sigterm_fd[2]; |
| 12 | |
| 13 | static constexpr char message[] = |
| 14 | "\nA signal was received. A second signal will force Dolphin to stop.\n"; |
| 15 | |
| 16 | SignalDaemon::SignalDaemon(QObject* parent) : QObject(parent) |
| 17 | { |
| 18 | if (socketpair(AF_UNIX, SOCK_STREAM, 0, s_sigterm_fd)) |
| 19 | qFatal("Couldn't create TERM socketpair"); |
| 20 | |
| 21 | m_term = new QSocketNotifier(s_sigterm_fd[1], QSocketNotifier::Read, this); |
| 22 | connect(m_term, &QSocketNotifier::activated, this, &SignalDaemon::OnNotifierActivated); |
| 23 | } |
| 24 | |
| 25 | SignalDaemon::~SignalDaemon() |
| 26 | { |
| 27 | close(s_sigterm_fd[0]); |
| 28 | close(s_sigterm_fd[1]); |
| 29 | } |
| 30 | |
| 31 | void SignalDaemon::OnNotifierActivated() |
| 32 | { |
| 33 | m_term->setEnabled(false); |
| 34 | |
| 35 | char tmp; |
| 36 | if (read(s_sigterm_fd[1], &tmp, sizeof(char)) != sizeof(char)) |
| 37 | { |
| 38 | // Not much we can do here. |
| 39 | } |
| 40 | |
| 41 | m_term->setEnabled(true); |
| 42 | |
| 43 | emit InterruptReceived(); |
| 44 | } |
| 45 | |
| 46 | void SignalDaemon::HandleInterrupt(int) |
| 47 | { |
| 48 | if (write(STDERR_FILENO, message, sizeof(message)) != sizeof(message)) |
| 49 | { |
| 50 | // Not much we can do here. |
| 51 | } |
| 52 | |
| 53 | char a = 1; |
| 54 | if (write(s_sigterm_fd[0], &a, sizeof(a)) != sizeof(a)) |
| 55 | { |
| 56 | // Not much we can do here. |
| 57 | } |
| 58 | } |