common: move utils_create_lock_file to its own file
[lttng-tools.git] / src / common / utils.c
index 210a7a6a1e1b6860fba64f2b82a842b5311ff7f2..a2b86d5c320af65a1b4f0b06aef730139abb051b 100644 (file)
@@ -224,77 +224,44 @@ end:
 LTTNG_HIDDEN
 int utils_create_pid_file(pid_t pid, const char *filepath)
 {
-       int ret;
-       FILE *fp;
+       int ret, fd = -1;
+       FILE *fp = NULL;
 
        assert(filepath);
 
-       fp = fopen(filepath, "w");
+       fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR |S_IWUSR | S_IRGRP | S_IROTH);
+       if (fd < 0) {
+               PERROR("open file %s", filepath);
+               ret = -1;
+               goto error;
+       }
+
+       fp = fdopen(fd, "w");
        if (fp == NULL) {
-               PERROR("open pid file %s", filepath);
+               PERROR("fdopen file %s", filepath);
                ret = -1;
+               if (close(fd)) {
+                       PERROR("Failed to close `%s` file descriptor while handling fdopen error", filepath);
+               }
+
                goto error;
        }
 
        ret = fprintf(fp, "%d\n", (int) pid);
        if (ret < 0) {
-               PERROR("fprintf pid file");
+               PERROR("fprintf file %s", filepath);
+               ret = -1;
                goto error;
        }
 
-       if (fclose(fp)) {
-               PERROR("fclose");
-       }
-       DBG("Pid %d written in file %s", (int) pid, filepath);
+       DBG("'%d' written in file %s", (int) pid, filepath);
        ret = 0;
-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;
-       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;
+       if (fp && fclose(fp)) {
+               PERROR("fclose file %s", filepath);
+       }
+       return ret;
 }
 
 /*
This page took 0.024021 seconds and 4 git commands to generate.