File: daemonize.c

package info (click to toggle)
minissdpd 1.5.20190210-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 484 kB
  • sloc: ansic: 4,944; sh: 296; makefile: 99
file content (129 lines) | stat: -rw-r--r-- 2,141 bytes parent folder | download | duplicates (8)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* $Id: daemonize.c,v 1.14 2018/04/22 19:36:58 nanard Exp $ */
/* MiniUPnP project
 * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
 * (c) 2006 Thomas Bernard
 * This software is subject to the conditions detailed
 * in the LICENCE file provided within the distribution */

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

#include "daemonize.h"
#include "config.h"

#ifndef USE_DAEMON

int
daemonize(void)
{
	int pid, i;

	switch(fork())
	{
	/* fork error */
	case -1:
		perror("fork()");
		exit(1);

	/* child process */
	case 0:
		/* obtain a new process group */
		if( (pid = setsid()) < 0)
		{
			perror("setsid()");
			exit(1);
		}

		/* close all descriptors */
		for (i=getdtablesize();i>=0;--i) close(i);

		i = open("/dev/null", O_RDWR); /* open stdin */
		dup(i); /* stdout */
		dup(i); /* stderr */

		umask(027);
		chdir("/"); /* chdir to /tmp ? */

		return pid;

	/* parent process */
	default:
		exit(0);
	}
}
#endif

int
writepidfile(const char * fname, int pid)
{
	char pidstring[16];
	int pidstringlen;
	int pidfile;

	if(!fname || fname[0] == '\0')
		return -1;

	if( (pidfile = open(fname, O_WRONLY|O_CREAT, 0644)) < 0)
	{
		syslog(LOG_ERR, "Unable to open pidfile for writing %s: %m", fname);
		return -1;
	}

	pidstringlen = snprintf(pidstring, sizeof(pidstring), "%d\n", pid);
	if(pidstringlen <= 0)
	{
		syslog(LOG_ERR,
			"Unable to write to pidfile %s: snprintf(): FAILED", fname);
		close(pidfile);
		return -1;
	}
	else
	{
		if(write(pidfile, pidstring, pidstringlen) < 0)
			syslog(LOG_ERR, "Unable to write to pidfile %s: %m", fname);
	}

	close(pidfile);

	return 0;
}

int
checkforrunning(const char * fname)
{
	char buffer[64];
	int pidfile;
	pid_t pid;

	if(!fname || fname[0] == '\0')
		return -1;

	if( (pidfile = open(fname, O_RDONLY)) < 0)
		return 0;

	memset(buffer, 0, 64);

	if(read(pidfile, buffer, 63))
	{
		if( (pid = atol(buffer)) > 0)
		{
			if(!kill(pid, 0))
			{
				close(pidfile);
				return -2;
			}
		}
	}

	close(pidfile);

	return 0;
}