common: move utils_create_lock_file to its own file
[lttng-tools.git] / src / common / lockfile.c
CommitLineData
f9431861
JG
1/*
2 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 *
5 * SPDX-License-Identifier: LGPL-2.1-only
6 *
7 */
8
9#include <common/error.h>
10#include <common/lockfile.h>
11#include <common/macros.h>
12
13#include <assert.h>
14
15#ifdef HAVE_FLOCK
16
17#else /* HAVE_FLOCK */
18
19#include <fcntl.h>
20
21int utils_create_lock_file(const char *filepath)
22{
23 int ret;
24 int fd;
25 struct flock lock;
26
27 assert(filepath);
28
29 memset(&lock, 0, sizeof(lock));
30 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
31 if (fd < 0) {
32 PERROR("open lock file %s", filepath);
33 fd = -1;
34 goto error;
35 }
36
37 /*
38 * Attempt to lock the file. If this fails, there is
39 * already a process using the same lock file running
40 * and we should exit.
41 */
42 lock.l_whence = SEEK_SET;
43 lock.l_type = F_WRLCK;
44
45 ret = fcntl(fd, F_SETLK, &lock);
46 if (ret == -1) {
47 PERROR("fcntl lock file");
48 ERR("Could not get lock file %s, another instance is running.", filepath);
49 if (close(fd)) {
50 PERROR("close lock file");
51 }
52 fd = ret;
53 goto error;
54 }
55
56error:
57 return fd;
58}
59
60#endif /* HAVE_FLOCK */
This page took 0.02467 seconds and 4 git commands to generate.