dotlock.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* $Id$
  2. *
  3. * isync - IMAP4 to maildir mailbox synchronizer
  4. * Copyright (C) 2002 Michael R. Elkins <me@mutt.org>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. /*
  21. * this file contains routines to establish a mutex using a `dotlock' file
  22. */
  23. #include <unistd.h>
  24. #include <fcntl.h>
  25. #include <sys/stat.h>
  26. #if TESTING
  27. #include <stdio.h>
  28. #endif
  29. #include "dotlock.h"
  30. static struct flock lck = { 0, SEEK_SET, 0, 0, 0 };
  31. static void make_lock (int type)
  32. {
  33. lck.l_type = type;
  34. lck.l_pid = getpid ();
  35. }
  36. int dotlock_lock (const char *path, int *fd)
  37. {
  38. *fd = open (path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  39. if (*fd == -1)
  40. return -1;
  41. make_lock (F_WRLCK);
  42. if (fcntl (*fd, F_SETLKW, &lck))
  43. {
  44. close (*fd);
  45. *fd = -1;
  46. return -1;
  47. }
  48. return 0;
  49. }
  50. int dotlock_unlock (int *fd)
  51. {
  52. int r = 0;
  53. if (*fd != -1)
  54. {
  55. make_lock (F_UNLCK);
  56. if (fcntl (*fd, F_SETLKW, &lck))
  57. r = -1;
  58. close (*fd);
  59. *fd = -1;
  60. }
  61. return r;
  62. }
  63. #if TESTING
  64. int main (void)
  65. {
  66. int fd;
  67. if (dotlock_lock ("./lock", &fd))
  68. {
  69. perror ("dotlock_lock");
  70. goto done;
  71. }
  72. puts("sleeping for 5 seconds");
  73. sleep(5);
  74. if (dotlock_unlock (&fd))
  75. {
  76. perror ("dotlock_lock");
  77. }
  78. done:
  79. exit (0);
  80. }
  81. #endif