分类: LINUX
2007-03-02 23:48:39
1 2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include 14 #include 15 |
16 void daemonize(const char *prgname, ...) 17 { 18 va_list args; 19 char buf[512]; 20 int pid, i; 21 struct sigaction act, oldact; 22 struct rlimit lim; 23 24 /* Detach controlling terminal */ 25 if ((pid = fork()) < 0) 26 exit(1); 27 else if (pid > 0) 28 _exit(0); 29 setsid(); 30 |
31 /* Avoid owning controlling terminal again */ 32 memset(&act, 0, sizeof(act)); 33 act.sa_handler = SIG_IGN; 34 sigemptyset(&act.sa_mask); 35 sigaction(SIGHUP, &act, &oldact); 36 if ((pid = fork()) < 0) 37 exit(1); 38 else if (pid > 0) 39 _exit(0); 40 /* Wait for the death of it's parent. */ 41 while (getppid() != 1) 42 ; 43 sigaction(SIGHUP, &oldact, NULL); 44 |
45 /* Deal with file operations */ 46 umask(0); 47 if (chdir("/") < 0) 48 exit(1); 49 if (getrlimit(RLIMIT_NOFILE, &lim) < 0) 50 exit(1); 51 if (lim.rlim_cur == RLIM_INFINITY) 52 lim.rlim_cur = 1024; 53 for (i = 0; i < lim.rlim_cur; i ++) { 54 if (close(i) < 0 && errno != EBADF) 55 exit(1); 56 } 57 if (open("/dev/null", O_RDWR) < 0 58 || dup(0) < 0 59 || dup(0) < 0) 60 exit(1); 61 |
62 /* Ignore all traditional signals */ 63 for (i = 1; i < 32; i ++) 64 sigaction(i, &act, NULL); 65 |
66 /* Initialize the log file */ 67 va_start(args, prgname); 68 vsnprintf(buf, sizeof(buf), prgname, args); 69 va_end(args); 70 openlog(buf, LOG_CONS | LOG_PID, LOG_DAEMON); 71 } 72 |
96 int uniqued(const char *prgname) 97 { 98 char buf[512]; 99 int fd, retval = -1; 100 101 assert(prgname != NULL); 102 snprintf(buf, sizeof(buf), "/var/run/%s.pid", prgname); 103 if ((fd = open(buf, O_RDWR | O_CREAT)) < 0) 104 goto out; 105 if (flock(fd, LOCK_EX | LOCK_NB) < 0) { 106 if (errno == EWOULDBLOCK) 107 retval = 0; 108 else 109 unlink(buf); 110 goto err; 111 } 112 if (ftruncate(fd, 0) < 0) 113 goto err; 114 snprintf(buf, sizeof(buf), "%ld\n", (long)getpid()); 115 if (write(fd, buf, strlen(buf)) != strlen(buf)) 116 goto err; 117 retval = fd; 118 119 out: 120 return retval; 121 122 err: 123 while (close(fd) < 0 && errno == EINTR) 124 ; 125 goto out; 126 } |