File: pid.c

package info (click to toggle)
mailleds 0.93-13
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 152 kB
  • ctags: 107
  • sloc: ansic: 865; makefile: 121
file content (84 lines) | stat: -rw-r--r-- 1,795 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#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 int opt_maildir;
extern char opt_q;
extern char *pid_filename;
extern char *username;
extern char *opt_m;

void set_pidfilename(void)
{
	int size, i, j=0;
	if(opt_maildir == 0)
		size = (strlen(PIDFILE_DIR) + strlen("/mailleds-") + strlen(username) + strlen(".pid") + 1);
	else
		size = (strlen(PIDFILE_DIR) + strlen("/mailleds-") + strlen(username) + strlen(".pid") + 2);

	if(opt_maildir == 1 && opt_m) {
		i=strlen(opt_m);
		while(i && opt_m[i-1]!='/')
			--i;
		j=strlen(opt_m)-i;
		size+=j;
	}

	pid_filename = (char *) xmalloc(size);

	if(j) {
		sprintf(pid_filename, "%s/mailleds-%s-%s.pid", PIDFILE_DIR, username, opt_m+i);
	} else {
		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);
	}
}