1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
/*
daemon -- functions for running as daemon
Copyright (C) 2003 Pedro Zorzenon Neto <pzn@autsens.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "daemon.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
void run_daemon_run (char * name, int uid, int gid) {
daemon_fork();
daemon_pid (name);
daemon_drop (uid, gid);
daemon_tty ();
daemon_null ();
}
void daemon_fork (void) {
pid_t pid;
pid = fork ();
if (pid<0)
{
perror("fork error");
abort();
}
if (pid != 0)
{
/* parent will terminate */
exit(0);
}
/* this is the child */
}
void daemon_pid (char * name) {
FILE * fh;
char * s;
s = malloc( sizeof(char)*
( strlen(DAEMON_PIDPREFIX) +
strlen(name) +
strlen(DAEMON_PIDSUFFIX) + 1 ));
assert(s != NULL);
sprintf(s, "%s%s%s", DAEMON_PIDPREFIX, name, DAEMON_PIDSUFFIX);
/* write to PID file */
fh=fopen(s, "w");
/* we will continue without errors if PID file failed */
if (fh != NULL)
{
fprintf(fh, "%d\n", getpid());
fclose(fh);
}
free(s);
}
void daemon_drop (int uid, int gid) {
if (gid != -1)
{
setgid (gid);
}
if (uid != -1)
{
setuid (uid);
}
}
void daemon_tty (void) {
/* lets remove the controlling tty */
if (setsid() == -1)
{
/* failed */
perror("setsid error");
abort();
}
}
void daemon_null (void) {
FILE * fh;
/* redirect stdin, stdout, stderr to /dev/null */
fh=freopen("/dev/null", "r", stdin);
if (fh == NULL) {
perror("could not redirect stdin:");
abort();
}
fh=freopen("/dev/null", "w", stdout);
if (fh == NULL) {
perror("could not redirect stdout:");
abort();
}
fh=freopen("/dev/null", "w", stderr);
if (fh == NULL) {
perror("could not redirect stderr:");
abort();
}
}
|