File: daemon.c

package info (click to toggle)
balboa 2.1.2%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,644 kB
  • sloc: ansic: 10,604; makefile: 160; python: 127; sh: 103
file content (40 lines) | stat: -rw-r--r-- 672 bytes parent folder | download | duplicates (4)
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

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>

#include <daemon.h>

int daemonize() {
  pid_t pid1 = fork();
  if(pid1 < 0) {
    return (-1);
  } else if(pid1 != 0) {
    _exit(0);
  }
  pid_t sid = setsid();
  if(sid < 0) { return (-1); }
  pid_t pid2 = fork();
  if(pid2 < 0) {
    return (-1);
  } else if(pid2 != 0) {
    _exit(0);
  }

  for(int n = 0; n < 1024; n++) { close(n); }

  int fd = open("/dev/null", O_RDWR);
  if(fd < 0) { return (0); }
  dup2(fd, 0);
  dup2(fd, 1);
  dup2(fd, 2);

  return (0);
}