|
- #include <stdio.h>
- #include <stdlib.h>
- #include <syslog.h>
- #include <sys/resource.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <signal.h>
- void
- daemonize(const char *cmd)
- {
- int i, fd0, fd1, fd2;
- pid_t pid;
- struct rlimit rl;
- struct sigaction sa;
-
- umask(0);
-
- if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
- printf("getrlimit failed");
- exit(1);
- }
-
- if ((pid = fork()) < 0) {
- printf("first fork failed");
- exit(1);
- } else if (pid > 0) {
- exit(0);
- }
-
- setsid();
-
- sa.sa_handler = SIG_IGN;
- sigemptyset(&sa.sa_mask);
- sa.sa_flags = 0;
- if (sigaction(SIGHUP, &sa, NULL) < 0) {
- printf("sigaction failed");
- exit(1);
- }
- if ((pid = fork()) < 0) {
- prinrf("second failed");
- exit(1);
- } else if (pid > 0) {
- exit(0);
- }
-
- if (chdir("/") < 0) {
- printf("chdir failed");
- exit(1);
- }
-
- if (rl.rlim_max == RLIM_INFINITY)
- rl.rlim_max = 1024;
- for (i = 0; i < rl.rlim_max; i++)
- close(i);
-
- fd0 = open("/dev/null", O_RDWR);
- fd1 = dup(0);
- fd2 = dup(0);
-
- openlog(cmd, LOG_CONS, LOG_DAEMON);
- if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
- syslog(LOG_ERR, "unexpected file descriptor %d %d %d", fd0, fd1, fd2);
- exit(1);
- }
- }
复制代码
上面是一个后台进程初始化代码,这里我有几个疑问:
第一:umask(0),这样的话岂不是任何用户都可以写由该进程创建的文件了吗
第二:为什么要忽略SIGHUP信号呢 |
|