dotlock.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 "dotlock.h"
  27. #include <unistd.h>
  28. #include <string.h>
  29. #include <fcntl.h>
  30. #include <sys/stat.h>
  31. #if TESTING
  32. #include <stdio.h>
  33. #endif
  34. int dotlock_lock (const char *path, int *fd)
  35. {
  36. struct flock lck;
  37. *fd = open (path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  38. if (*fd == -1)
  39. return -1;
  40. memset (&lck, 0, sizeof(lck));
  41. #if SEEK_SET != 0
  42. lck.l_whence = SEEK_SET;
  43. #endif
  44. #if F_WRLCK != 0
  45. lck.l_type = F_WRLCK;
  46. #endif
  47. if (fcntl (*fd, F_SETLK, &lck))
  48. {
  49. close (*fd);
  50. *fd = -1;
  51. return -1;
  52. }
  53. return 0;
  54. }
  55. int dotlock_unlock (int *fd)
  56. {
  57. int r = 0;
  58. struct flock lck;
  59. if (*fd != -1)
  60. {
  61. memset (&lck, 0, sizeof(lck));
  62. #if SEEK_SET != 0
  63. lck.l_whence = SEEK_SET;
  64. #endif
  65. #if F_UNLCK != 0
  66. lck.l_type = F_UNLCK;
  67. #endif
  68. if (fcntl (*fd, F_SETLK, &lck))
  69. r = -1;
  70. close (*fd);
  71. *fd = -1;
  72. }
  73. return r;
  74. }
  75. #if TESTING
  76. int main (void)
  77. {
  78. int fd;
  79. if (dotlock_lock ("./lock", &fd))
  80. {
  81. perror ("dotlock_lock");
  82. goto done;
  83. }
  84. puts ("sleeping for 5 seconds");
  85. sleep(5);
  86. if (dotlock_unlock (&fd))
  87. {
  88. perror ("dotlock_unlock");
  89. }
  90. done:
  91. exit (0);
  92. }
  93. #endif