catboy/sandman.m

89 lines
2.2 KiB
Matlab
Raw Normal View History

2019-07-02 22:04:27 +00:00
/* Copyright (C) 2019 C. McEnroe <june@causal.agency>
2018-11-30 20:41:21 +00:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#import <Cocoa/Cocoa.h>
#import <err.h>
#import <signal.h>
#import <stdlib.h>
#import <sysexits.h>
#import <unistd.h>
2019-07-02 22:04:27 +00:00
static volatile sig_atomic_t sleeping;
static void sigchld(int sig) {
2018-11-30 20:41:21 +00:00
(void)sig;
int status;
pid_t pid = wait(&status);
2018-12-01 15:28:00 +00:00
if (pid < 0) _exit(EX_OSERR);
2019-07-02 22:04:27 +00:00
if (WIFSIGNALED(status) && WTERMSIG(status) != SIGHUP) {
2018-11-30 20:41:21 +00:00
_exit(128 + WTERMSIG(status));
2019-07-02 22:04:27 +00:00
} else if (!sleeping) {
2018-11-30 20:41:21 +00:00
_exit(WEXITSTATUS(status));
}
}
2019-07-02 22:04:27 +00:00
static pid_t spawn(char *argv[]) {
pid_t pid = fork();
if (pid < 0) err(EX_OSERR, "fork");
if (pid) return pid;
execvp(argv[0], argv);
err(EX_NOINPUT, "%s", argv[0]);
}
static pid_t pid;
2018-11-30 20:41:21 +00:00
int main(int argc, char *argv[]) {
if (argc < 2) return EX_USAGE;
2018-12-01 15:28:00 +00:00
sigset_t mask;
sigemptyset(&mask);
2019-07-02 22:04:27 +00:00
struct sigaction action = {
.sa_handler = sigchld,
2018-12-01 15:28:00 +00:00
.sa_mask = mask,
.sa_flags = SA_NOCLDSTOP | SA_RESTART,
2018-12-01 15:28:00 +00:00
};
2019-07-02 22:04:27 +00:00
sigaction(SIGCHLD, &action, NULL);
2018-11-30 20:41:21 +00:00
2019-07-02 22:04:27 +00:00
pid = spawn(&argv[1]);
2018-11-30 20:41:21 +00:00
2018-11-30 22:16:59 +00:00
[
[[NSWorkspace sharedWorkspace] notificationCenter]
addObserverForName: NSWorkspaceWillSleepNotification
object: nil
queue: nil
2018-11-30 22:16:59 +00:00
usingBlock: ^(NSNotification *note) {
(void)note;
2019-07-02 22:04:27 +00:00
sleeping = 1;
2018-12-04 20:38:22 +00:00
int error = kill(pid, SIGHUP);
2018-11-30 22:16:59 +00:00
if (error) err(EX_UNAVAILABLE, "kill %d", pid);
}
];
2018-11-30 20:41:21 +00:00
2019-07-02 22:04:27 +00:00
[
[[NSWorkspace sharedWorkspace] notificationCenter]
addObserverForName: NSWorkspaceDidWakeNotification
object: nil
queue: nil
usingBlock: ^(NSNotification *note) {
(void)note;
sleeping = 0;
pid = spawn(&argv[1]);
}
];
2018-11-30 20:41:21 +00:00
[[NSApplication sharedApplication] run];
}