aboutsummaryrefslogtreecommitdiff
path: root/libutil/op_lockfile.c
blob: 26e3249f83e1c92958bc38d2fdac75cfeb75932c (plain)
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
/**
 * @file op_lockfile.c
 * PID-based lockfile management
 *
 * @remark Copyright 2002 OProfile authors
 * @remark Read the file COPYING
 *
 * @author John Levon
 * @author Philippe Elie
 */

#include "op_lockfile.h"
#include "op_file.h"

#include <errno.h>

#include <sys/types.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

static pid_t op_read_lock_file(char const * file)
{
	FILE * fp;
	pid_t value;

	fp = fopen(file, "r");
	if (fp == NULL)
		return 0;

	if (fscanf(fp, "%d", &value) != 1) {
		fclose(fp);
		return 0;
	}

	fclose(fp);

	return value;
}


int op_write_lock_file(char const * file)
{
	FILE * fp;

	if (op_file_readable(file)) {
		pid_t pid = op_read_lock_file(file);

		/* FIXME: ESRCH vs. EPERM */
		if (kill(pid, 0)) {
			int err = unlink(file);
			fprintf(stderr, "Removing stale lock file %s\n",
				file);
			if (err)
				return err;
		} else {
			return EEXIST;
		}
	}

	fp = fopen(file, "w");
	if (!fp)
		return errno;

	fprintf(fp, "%d", getpid());
	fclose(fp);

	return 0;
}