File: pid.c

package info (click to toggle)
mailleds 0.93-9
  • links: PTS
  • area: main
  • in suites: woody
  • size: 156 kB
  • ctags: 108
  • sloc: ansic: 816; makefile: 107; sh: 17
file content (64 lines) | stat: -rw-r--r-- 1,379 bytes parent folder | download
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
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <signal.h>
#include <errno.h>
#include "config.h"
#include "mailleds.h"

extern int uid;
extern int euid;
extern int pid;
extern char opt_q;
extern char *pid_filename;
extern char *username;

void set_pidfilename(void)
{
	int size = (strlen(PIDFILE_DIR) + strlen("/mailleds-") + strlen(username) + strlen(".pid") + 1);
	pid_filename = (char *) xmalloc(size);
	sprintf(pid_filename, "%s/mailleds-%s.pid", PIDFILE_DIR, username);
}

void write_pidfile(void)
{
	FILE *pidfile;
	if ((pidfile = fopen(pid_filename, "w")) == (FILE *) NULL) {
		fprintf(stderr, "mailleds: could not write pidfile %s\n", pid_filename);
		exit(-2);
	}
	fprintf(pidfile, "%d", pid);
	fclose(pidfile);
}

int get_pid_from_file(char *pid_filename)
{
	char buf[1024];
	char *inc;
	FILE *pid_file;
	if ((pid_file = fopen(pid_filename, "r"))) {
		fgets(buf, 1024, pid_file);
		fclose(pid_file);
		inc = buf;
		while (isspace(*inc))
			inc++;
		return (atoi(inc));
	} else {
		return (0);
	}
}

int pid_check(void)
{
	int test_pid;
	test_pid = get_pid_from_file(pid_filename);
	if (test_pid) {
		if (kill(test_pid, 0) < 0 && errno == ESRCH)
			return (1);	/* pidfile is stale -- override. */
		if (!opt_q)
			fprintf(stderr, "mailleds: mailleds process %d already running for %s\n", test_pid, username);
		exit(-2);
	} else {
		return (1);
	}
}