X-Git-Url: https://git.lttng.org/?p=lttng-tools.git;a=blobdiff_plain;f=src%2Fcommon%2Flockfile.c;fp=src%2Fcommon%2Flockfile.c;h=a34838c553f13f795b8127d3d83947c95900b9be;hp=0000000000000000000000000000000000000000;hb=f9431861198d04bfa0e14cbe65360412de67f40a;hpb=f03ea3f43450abb1a1ea704044e1e8c78cfc0b4c diff --git a/src/common/lockfile.c b/src/common/lockfile.c new file mode 100644 index 000000000..a34838c55 --- /dev/null +++ b/src/common/lockfile.c @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2012 David Goulet + * Copyright (C) 2013 Jérémie Galarneau + * + * SPDX-License-Identifier: LGPL-2.1-only + * + */ + +#include +#include +#include + +#include + +#ifdef HAVE_FLOCK + +#else /* HAVE_FLOCK */ + +#include + +int utils_create_lock_file(const char *filepath) +{ + int ret; + int fd; + struct flock lock; + + assert(filepath); + + memset(&lock, 0, sizeof(lock)); + fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + if (fd < 0) { + PERROR("open lock file %s", filepath); + fd = -1; + goto error; + } + + /* + * Attempt to lock the file. If this fails, there is + * already a process using the same lock file running + * and we should exit. + */ + lock.l_whence = SEEK_SET; + lock.l_type = F_WRLCK; + + ret = fcntl(fd, F_SETLK, &lock); + if (ret == -1) { + PERROR("fcntl lock file"); + ERR("Could not get lock file %s, another instance is running.", filepath); + if (close(fd)) { + PERROR("close lock file"); + } + fd = ret; + goto error; + } + +error: + return fd; +} + +#endif /* HAVE_FLOCK */