| 1 | /* | 
|---|
| 2 | * synergy -- mouse and keyboard sharing utility | 
|---|
| 3 | * Copyright (C) 2002 Chris Schoeneman | 
|---|
| 4 | * | 
|---|
| 5 | * This package is free software; you can redistribute it and/or | 
|---|
| 6 | * modify it under the terms of the GNU General Public License | 
|---|
| 7 | * found in the file COPYING that should have accompanied this file. | 
|---|
| 8 | * | 
|---|
| 9 | * This package is distributed in the hope that it will be useful, | 
|---|
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | 
|---|
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | 
|---|
| 12 | * GNU General Public License for more details. | 
|---|
| 13 | */ | 
|---|
| 14 |  | 
|---|
| 15 | #include "CArchDaemonUnix.h" | 
|---|
| 16 | #include "XArchUnix.h" | 
|---|
| 17 | #include <unistd.h> | 
|---|
| 18 | #include <sys/types.h> | 
|---|
| 19 | #include <sys/stat.h> | 
|---|
| 20 | #include <fcntl.h> | 
|---|
| 21 | #include <errno.h> | 
|---|
| 22 |  | 
|---|
| 23 | // | 
|---|
| 24 | // CArchDaemonUnix | 
|---|
| 25 | // | 
|---|
| 26 |  | 
|---|
| 27 | CArchDaemonUnix::CArchDaemonUnix() | 
|---|
| 28 | { | 
|---|
| 29 | // do nothing | 
|---|
| 30 | } | 
|---|
| 31 |  | 
|---|
| 32 | CArchDaemonUnix::~CArchDaemonUnix() | 
|---|
| 33 | { | 
|---|
| 34 | // do nothing | 
|---|
| 35 | } | 
|---|
| 36 |  | 
|---|
| 37 | int | 
|---|
| 38 | CArchDaemonUnix::daemonize(const char* name, DaemonFunc func) | 
|---|
| 39 | { | 
|---|
| 40 | // fork so shell thinks we're done and so we're not a process | 
|---|
| 41 | // group leader | 
|---|
| 42 | switch (fork()) { | 
|---|
| 43 | case -1: | 
|---|
| 44 | // failed | 
|---|
| 45 | throw XArchDaemonFailed(new XArchEvalUnix(errno)); | 
|---|
| 46 |  | 
|---|
| 47 | case 0: | 
|---|
| 48 | // child | 
|---|
| 49 | break; | 
|---|
| 50 |  | 
|---|
| 51 | default: | 
|---|
| 52 | // parent exits | 
|---|
| 53 | exit(0); | 
|---|
| 54 | } | 
|---|
| 55 |  | 
|---|
| 56 | // become leader of a new session | 
|---|
| 57 | setsid(); | 
|---|
| 58 |  | 
|---|
| 59 | // chdir to root so we don't keep mounted filesystems points busy | 
|---|
| 60 | chdir("/"); | 
|---|
| 61 |  | 
|---|
| 62 | // mask off permissions for any but owner | 
|---|
| 63 | umask(077); | 
|---|
| 64 |  | 
|---|
| 65 | // close open files.  we only expect stdin, stdout, stderr to be open. | 
|---|
| 66 | close(0); | 
|---|
| 67 | close(1); | 
|---|
| 68 | close(2); | 
|---|
| 69 |  | 
|---|
| 70 | // attach file descriptors 0, 1, 2 to /dev/null so inadvertent use | 
|---|
| 71 | // of standard I/O safely goes in the bit bucket. | 
|---|
| 72 | open("/dev/null", O_RDONLY); | 
|---|
| 73 | open("/dev/null", O_RDWR); | 
|---|
| 74 | dup(1); | 
|---|
| 75 |  | 
|---|
| 76 | // invoke function | 
|---|
| 77 | return func(1, &name); | 
|---|
| 78 | } | 
|---|