Fix: Create a lock file to prevent multiple session daemons
[lttng-tools.git] / src / common / utils.c
index b640b950e7e3d88ac95a966d60e76acaa1a88121..ff6d1c22337200e69e24807b1c871530ce6ea09e 100644 (file)
@@ -30,6 +30,7 @@
 #include <inttypes.h>
 #include <grp.h>
 #include <pwd.h>
+#include <sys/file.h>
 
 #include <common/common.h>
 #include <common/runas.h>
@@ -468,6 +469,44 @@ error:
        return ret;
 }
 
+/*
+ * Create lock file to the given path and filename.
+ * Returns the associated file descriptor, -1 on error.
+ */
+LTTNG_HIDDEN
+int utils_create_lock_file(const char *filepath)
+{
+       int ret;
+       int fd;
+
+       assert(filepath);
+
+       fd = open(filepath, O_CREAT,
+               O_WRONLY | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+       if (fd < 0) {
+               PERROR("open lock file %s", filepath);
+               ret = -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.
+        */
+       ret = flock(fd, LOCK_EX | LOCK_NB);
+       if (ret) {
+               WARN("Could not get lock file %s, another instance is running.",
+                       filepath);
+               close(fd);
+               fd = ret;
+               goto error;
+       }
+
+error:
+       return fd;
+}
+
 /*
  * Recursively create directory using the given path and mode.
  *
This page took 0.023281 seconds and 4 git commands to generate.