dotlock.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. int dotlock_lock (const char *path, int *fd)
  32. {
  33. *fd = open (path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  34. if (*fd == -1)
  35. return -1;
  36. lck.l_type = F_WRLCK;
  37. if (fcntl (*fd, F_SETLK, &lck))
  38. {
  39. close (*fd);
  40. *fd = -1;
  41. return -1;
  42. }
  43. return 0;
  44. }
  45. int dotlock_unlock (int *fd)
  46. {
  47. int r = 0;
  48. if (*fd != -1)
  49. {
  50. lck.l_type = F_UNLCK;
  51. if (fcntl (*fd, F_SETLKW, &lck))
  52. r = -1;
  53. close (*fd);
  54. *fd = -1;
  55. }
  56. return r;
  57. }
  58. #if TESTING
  59. int main (void)
  60. {
  61. int fd;
  62. if (dotlock_lock ("./lock", &fd))
  63. {
  64. perror ("dotlock_lock");
  65. goto done;
  66. }
  67. puts("sleeping for 5 seconds");
  68. sleep(5);
  69. if (dotlock_unlock (&fd))
  70. {
  71. perror ("dotlock_unlock");
  72. }
  73. done:
  74. exit (0);
  75. }
  76. #endif