dotlock.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. * As a special exception, isync may be linked with the OpenSSL library,
  21. * despite that library's more restrictive license.
  22. */
  23. /*
  24. * this file contains routines to establish a mutex using a `dotlock' file
  25. */
  26. #include <unistd.h>
  27. #include <fcntl.h>
  28. #include <sys/stat.h>
  29. #if TESTING
  30. #include <stdio.h>
  31. #endif
  32. #include "dotlock.h"
  33. static struct flock lck = { 0, SEEK_SET, 0, 0, 0 };
  34. int dotlock_lock (const char *path, int *fd)
  35. {
  36. *fd = open (path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  37. if (*fd == -1)
  38. return -1;
  39. lck.l_type = F_WRLCK;
  40. if (fcntl (*fd, F_SETLK, &lck))
  41. {
  42. close (*fd);
  43. *fd = -1;
  44. return -1;
  45. }
  46. return 0;
  47. }
  48. int dotlock_unlock (int *fd)
  49. {
  50. int r = 0;
  51. if (*fd != -1)
  52. {
  53. lck.l_type = F_UNLCK;
  54. if (fcntl (*fd, F_SETLK, &lck))
  55. r = -1;
  56. close (*fd);
  57. *fd = -1;
  58. }
  59. return r;
  60. }
  61. #if TESTING
  62. int main (void)
  63. {
  64. int fd;
  65. if (dotlock_lock ("./lock", &fd))
  66. {
  67. perror ("dotlock_lock");
  68. goto done;
  69. }
  70. puts ("sleeping for 5 seconds");
  71. sleep(5);
  72. if (dotlock_unlock (&fd))
  73. {
  74. perror ("dotlock_unlock");
  75. }
  76. done:
  77. exit (0);
  78. }
  79. #endif