| 1 | /* Copyright © 2016 Bill Allombert |
| 2 | |
| 3 | This program is free software; you can redistribute it and/or modify |
| 4 | it under the terms of the GNU General Public License as published by |
| 5 | the Free Software Foundation; either version 2 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 General Public License for more details. |
| 12 | |
| 13 | Check the License for details. You should have received a copy of it, along |
| 14 | with the package; see the file 'COPYING'. If not, write to the Free Software |
| 15 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 16 | */ |
| 17 | |
| 18 | #include <stdio.h> |
| 19 | #include <stdlib.h> |
| 20 | #include <unistd.h> |
| 21 | #include <sys/types.h> |
| 22 | #include <sys/stat.h> |
| 23 | #include <sys/wait.h> |
| 24 | #include <fcntl.h> |
| 25 | #include <sys/ioctl.h> |
| 26 | #include "consolation.h" |
| 27 | |
| 28 | static int csl_daemon(void) |
| 29 | { |
| 30 | pid_t pid = fork(); |
| 31 | switch(pid) { |
| 32 | case -1: return 1; /* father, fork failed */ |
| 33 | case 0: |
| 34 | (void)setsid(); /* son becomes process group leader */ |
| 35 | if (fork()) exit(0); /* now son exits, also when fork fails */ |
| 36 | break; /* grandson: its father is the son, which exited, |
| 37 | * hence father becomes 'init', that'll take care of it */ |
| 38 | default: /* father, fork succeeded */ |
| 39 | (void)waitpid(pid,NULL,0); /* wait for son to exit, immediate */ |
| 40 | return 1; |
| 41 | } |
| 42 | /* grandson */ |
| 43 | return 0; |
| 44 | } |
| 45 | |
| 46 | int main(int argc, char **argv) |
| 47 | { |
| 48 | if (event_init(argc, argv)) |
| 49 | return 1; |
| 50 | if (nodaemon || !csl_daemon()) event_main(); |
| 51 | return 0; |
| 52 | } |