lock.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * libdpkg - Debian packaging suite library routines
  3. * lock.c - packages database locking
  4. *
  5. * Copyright © 1994,1995 Ian Jackson <ian@chiark.greenend.org.uk>
  6. *
  7. * This is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include <config.h>
  21. #include <compat.h>
  22. #include <sys/file.h>
  23. #include <assert.h>
  24. #include <errno.h>
  25. #include <string.h>
  26. #include <fcntl.h>
  27. #include <unistd.h>
  28. #include <stdlib.h>
  29. #include <dpkg/i18n.h>
  30. #include <dpkg/dpkg.h>
  31. #include <dpkg/dpkg-db.h>
  32. static void
  33. file_unlock_cleanup(int argc, void **argv)
  34. {
  35. int lockfd = *(int*)argv[0];
  36. struct flock fl;
  37. assert(lockfd >= 0);
  38. fl.l_type= F_UNLCK;
  39. fl.l_whence= SEEK_SET;
  40. fl.l_start= 0;
  41. fl.l_len= 0;
  42. if (fcntl(lockfd, F_SETLK, &fl) == -1)
  43. ohshite(_("unable to unlock dpkg status database"));
  44. }
  45. void
  46. file_unlock(void)
  47. {
  48. pop_cleanup(ehflag_normaltidy); /* Calls file_unlock_cleanup. */
  49. }
  50. /* lockfd must be allocated statically as its addresses is passed to
  51. * a cleanup handler. */
  52. void
  53. file_lock(int *lockfd, const char *filename,
  54. const char *emsg, const char *emsg_eagain)
  55. {
  56. struct flock fl;
  57. setcloexec(*lockfd, filename);
  58. fl.l_type = F_WRLCK;
  59. fl.l_whence = SEEK_SET;
  60. fl.l_start = 0;
  61. fl.l_len = 0;
  62. if (fcntl(*lockfd, emsg_eagain ? F_SETLK : F_SETLKW, &fl) == -1) {
  63. if (emsg_eagain && (errno == EACCES || errno == EAGAIN))
  64. ohshit(emsg_eagain);
  65. ohshite(emsg);
  66. }
  67. push_cleanup(file_unlock_cleanup, ~0, NULL, 0, 1, lockfd);
  68. }