common: move utils_create_lock_file to its own file
[lttng-tools.git] / src / common / lockfile.cpp
CommitLineData
51379287
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.hpp>
10#include <common/lockfile.hpp>
11#include <common/macros.hpp>
12
13#ifdef HAVE_FLOCK
14
15#else /* HAVE_FLOCK */
16
17#include <fcntl.h>
18
19int utils_create_lock_file(const char *filepath)
20{
21 int ret;
22 int fd;
23 struct flock lock;
24
25 LTTNG_ASSERT(filepath);
26
27 memset(&lock, 0, sizeof(lock));
28 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
29 if (fd < 0) {
30 PERROR("open lock file %s", filepath);
31 fd = -1;
32 goto error;
33 }
34
35 /*
36 * Attempt to lock the file. If this fails, there is
37 * already a process using the same lock file running
38 * and we should exit.
39 */
40 lock.l_whence = SEEK_SET;
41 lock.l_type = F_WRLCK;
42
43 ret = fcntl(fd, F_SETLK, &lock);
44 if (ret == -1) {
45 PERROR("fcntl lock file");
46 ERR("Could not get lock file %s, another instance is running.", filepath);
47 if (close(fd)) {
48 PERROR("close lock file");
49 }
50 fd = ret;
51 goto error;
52 }
53
54error:
55 return fd;
56}
57
58#endif /* HAVE_FLOCK */
This page took 0.024007 seconds and 4 git commands to generate.