/[projects]/smsdaemon/daemon.cpp
ViewVC logotype

Contents of /smsdaemon/daemon.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 114 - (show annotations) (download)
Sun Nov 2 20:14:20 2008 UTC (15 years, 6 months ago) by torben
File size: 2044 byte(s)
Enable compilation 4.3

1 #include <iostream>
2
3 #include <signal.h>
4 #include <fcntl.h>
5 #include <stdlib.h>
6 #include <cstring>
7
8 #include "daemon.h"
9 #include "common.h"
10
11
12
13 using namespace std;
14
15
16 void signal_handler(int sig)
17 {
18 switch(sig) {
19 case SIGHUP:
20 Common::instance()->logMessage("hangup signal catched");
21 break;
22
23 case SIGTERM:
24 Common::instance()->logMessage("terminate signal catched...exiting");
25 Common::instance()->mainContinue = false;
26 break;
27 }
28 }
29
30 void daemonCleanup()
31 {
32 unlink( Common::instance()->pidfile.c_str() );
33 }
34
35 void daemonize()
36 {
37 int i, lfp;
38 char str[10];
39 Common* cmn = Common::instance();
40
41 if (getuid() != 0)
42 {
43 cout << "Please start this daemon as root\n" << endl;
44 daemon_shutdown(0);
45 }
46
47
48 if (getppid() == 1) /* already a daemon */
49 return;
50
51 i=fork();
52
53 if (i<0) /* fork error */
54 daemon_shutdown(FORK_ERROR);
55 if (i>0) /* parent exits */
56 daemon_shutdown(0);
57 /* child daemon continues */
58
59 setsid(); /* obtain a new process group */
60
61 for (i=getdtablesize(); i>=0; --i)
62 close(i); /*close all descriptors*/
63
64 i=open("/dev/null", O_RDWR); /* handle std. io */
65 dup(i);
66 dup(i);
67
68 umask(027); /* set newly created file permissions */
69
70 chdir("/tmp"); /* change running directory*/
71
72 /*attempt to create lockfile and put a file-lock on it*/
73 lfp=open(cmn->pidfile.c_str(), O_RDWR|O_CREAT, 0640);
74 if (lfp<0) /* can not open */
75 daemon_shutdown(CANT_OPEN_LOCK);
76 if (lockf(lfp,F_TLOCK,0) < 0) /* can not lock */
77 daemon_shutdown(ALREADY_LOCKED);
78
79 /* first instance continues */
80 sprintf(str, "%d\n", getpid() ); /* record pid to lockfile */
81 write(lfp, str, strlen(str) );
82 //signal(SIGCHLD, SIG_IGN); /* ignore child */
83 signal(SIGTSTP, SIG_IGN); /* ignore tty signals */
84 signal(SIGTTOU, SIG_IGN);
85 signal(SIGTTIN, SIG_IGN);
86 signal(SIGHUP, signal_handler); /* catch hangup signal */
87 signal(SIGTERM, signal_handler); /* catch kill signal */
88
89 /*this program is now a daemon*/
90 setegid( cmn->gid );
91 seteuid( cmn->uid );
92 }

  ViewVC Help
Powered by ViewVC 1.1.20