IRC client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.2KB

  1. /* Copyright (C) 2019 C. McEnroe <june@causal.agency>
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU Affero General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU Affero General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Affero General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #import <Cocoa/Cocoa.h>
  17. #import <err.h>
  18. #import <signal.h>
  19. #import <stdlib.h>
  20. #import <sysexits.h>
  21. #import <unistd.h>
  22. static volatile sig_atomic_t sleeping;
  23. static void sigchld(int sig) {
  24. (void)sig;
  25. int status;
  26. pid_t pid = wait(&status);
  27. if (pid < 0) _exit(EX_OSERR);
  28. if (WIFSIGNALED(status) && WTERMSIG(status) != SIGHUP) {
  29. _exit(128 + WTERMSIG(status));
  30. } else if (!sleeping) {
  31. _exit(WEXITSTATUS(status));
  32. }
  33. }
  34. static pid_t spawn(char *argv[]) {
  35. pid_t pid = fork();
  36. if (pid < 0) err(EX_OSERR, "fork");
  37. if (pid) return pid;
  38. execvp(argv[0], argv);
  39. err(EX_NOINPUT, "%s", argv[0]);
  40. }
  41. static pid_t pid;
  42. int main(int argc, char *argv[]) {
  43. if (argc < 2) return EX_USAGE;
  44. sigset_t mask;
  45. sigemptyset(&mask);
  46. struct sigaction action = {
  47. .sa_handler = sigchld,
  48. .sa_mask = mask,
  49. .sa_flags = SA_NOCLDSTOP | SA_RESTART,
  50. };
  51. sigaction(SIGCHLD, &action, NULL);
  52. pid = spawn(&argv[1]);
  53. [
  54. [[NSWorkspace sharedWorkspace] notificationCenter]
  55. addObserverForName: NSWorkspaceWillSleepNotification
  56. object: nil
  57. queue: nil
  58. usingBlock: ^(NSNotification *note) {
  59. (void)note;
  60. sleeping = 1;
  61. int error = kill(pid, SIGHUP);
  62. if (error) err(EX_UNAVAILABLE, "kill %d", pid);
  63. }
  64. ];
  65. [
  66. [[NSWorkspace sharedWorkspace] notificationCenter]
  67. addObserverForName: NSWorkspaceDidWakeNotification
  68. object: nil
  69. queue: nil
  70. usingBlock: ^(NSNotification *note) {
  71. (void)note;
  72. sleeping = 0;
  73. pid = spawn(&argv[1]);
  74. }
  75. ];
  76. [[NSApplication sharedApplication] run];
  77. }