view common/linuxlockfile.c @ 1081:edbf5e5e88f4

(issue118) Extend verify_binary to carry an open file * binverify.c: Change result to a structure containing an open fptr Use in Memory data for windows verification. * mainwindow.cpp, selftest.c: Handle the returend structure * binverifytest.cpp: Test for the exclusive read and update signature. * listutil.c: Add optional fptr parameter to read_file
author Andre Heinecke <andre.heinecke@intevation.de>
date Thu, 11 Sep 2014 12:05:24 +0200
parents 20ca94680003
children a974b61a5cce
line wrap: on
line source
#ifndef WIN32

#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

#include "logging.h"

int
open_lockfile(char *path)
{
  int fd;
  char pidstr[20];
  size_t pidstrlen;
  struct flock lk;
  fd = open(path, O_RDWR | O_CREAT, 0600);
  if (fd != -1)
    {
      /* Get an exclusive lock on the whole file. */
      lk.l_type = F_WRLCK;
      lk.l_whence = SEEK_SET;
      lk.l_start = 0;
      lk.l_len = 0;
      if (fcntl(fd, F_SETLK, &lk) != -1)
        {
          /* FIXME: For extra security we should check if there is
             already a pid in the file.  If so we should check in
             /proc/$PID if there is still a process of the same name
             as ours running... */
          ftruncate(fd, 0);
          pidstrlen = (size_t)snprintf(pidstr, sizeof(pidstr), "%d", getpid());
          write(fd, pidstr, pidstrlen);
        }
      else
        {
          /* Lock can not be acquired.  Bail out... */
          close(fd);
          DEBUGPRINTF("Could not get an exclusive lock on %s.\n", path);
          return -1;
        }
    }
  else
    {
      DEBUGPRINTF("Failed to open lock file: %s.\n", path);
    }
  return fd;
}

void
close_lockfile(int fd)
{
  struct flock lk;

  /* Delete the PID from file. */
  /* We do this instead of trying to unlink the file. */
  ftruncate(fd, 0);

  /* Remove lock from the file. */
  lk.l_type = F_UNLCK;
  lk.l_whence = SEEK_SET;
  lk.l_start = 0;
  lk.l_len = 0;
  if (fcntl(fd, F_SETLK, &lk) == -1)
    {
      /* Lock can not be removed?!?  WTF? */
      DEBUGPRINTF("Could not remove lock from pid file. STRANGE!\n");
    }
  close(fd);
}

#endif /* Not WIN32 */

http://wald.intevation.org/projects/trustbridge/