pidentd  3.0.19
About: implementation of the RFC1413 identification server (more or less complete rewrite compared to version 2)
  Fossies Dox: pidentd-3.0.19.tar.gz  ("inofficial" and yet experimental doxygen-generated source code documentation)  

daemon.c
Go to the documentation of this file.
1 /*
2 ** daemon.c - Become a Unix daemon, and support functions.
3 **
4 ** Copyright (c) 1997 Peter Eriksson <pen@lysator.liu.se>
5 **
6 ** This program is free software; you can redistribute it and/or
7 ** modify it as you wish - as long as you don't claim that you wrote
8 ** it.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 */
14 
15 #include "config.h"
16 
17 #include <stdio.h>
18 #include <stdlib.h>
19 
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23 
24 #include <syslog.h>
25 #include <string.h>
26 #include <fcntl.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <signal.h>
30 
31 #include "pidentd.h"
32 
33 
34 /*
35 ** Fork and disassociate ourself from any controlling tty.
36 */
37 void
39 {
40  pid_t pid;
41  int i, fd;
42 
43 
44  pid = fork();
45  if (pid < 0)
46  {
47  syslog(LOG_ERR, "fork() failed: %m");
49  }
50  else if (pid > 0)
52 
53  signal(SIGTTOU, SIG_IGN);
54  signal(SIGTTIN, SIG_IGN);
55 #ifdef SIGTTSP
56  signal(SIGTTSP, SIG_IGN);
57 #endif
58 
59 #ifdef HAVE_SETSID
60  setsid();
61 #endif
62 
63  chdir("/");
64  umask(0);
65 
66  for (i = 0; i < 3; i++)
67  {
68  close(i);
69 
70  fd = s_open("/dev/null", O_RDWR);
71  if (fd != i)
72  {
73  dup2(fd, i);
74  close(fd);
75  }
76  }
77 }
78 
79 
80 /*
81 ** Create a (or truncate an existing) file containing
82 ** our process id number.
83 */
84 void
85 pidfile_create(const char *path)
86 {
87  int fd;
88  char buf[64];
89 
90 
91  fd = s_open(path, O_WRONLY|O_CREAT|O_TRUNC, 0644);
92  if (fd < 0)
93  {
94  syslog(LOG_ERR, "s_open(\"%s\", O_WRONLY): %m", path);
95  return;
96  }
97 
98  s_snprintf(buf, sizeof(buf), "%ld\n", (long) getpid());
99  if (s_write(fd, buf, strlen(buf)) < 0)
100  syslog(LOG_ERR, "s_write(fd, ..., %d): %m", fd, strlen(buf));
101 
102  s_close(fd);
103 }
104 
s_snprintf
int s_snprintf(char *buf, size_t bufsize, const char *format,...)
Definition: safeio.c:269
pidfile_create
void pidfile_create(const char *path)
Definition: daemon.c:85
pidentd.h
s_close
int s_close(int fd)
Definition: safeio.c:113
exit
#define exit
Definition: k_sunos510.c:38
s_open
int s_open(const char *path, int oflag,...)
Definition: safeio.c:44
become_daemon
void become_daemon(void)
Definition: daemon.c:38
s_write
ssize_t s_write(int fd, const char *buf, size_t len)
Definition: safeio.c:83
EXIT_SUCCESS
#define EXIT_SUCCESS
Definition: system.h:40
EXIT_FAILURE
#define EXIT_FAILURE
Definition: system.h:44