lock.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * libdpkg - Debian packaging suite library routines
  3. * lock.c - packages database locking
  4. *
  5. * Copyright (C) 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
  9. * published by the Free Software Foundation; either version 2,
  10. * or (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful, but
  13. * 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
  18. * License along with dpkg; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include <config.h>
  22. #include <unistd.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <errno.h>
  26. #include <unistd.h>
  27. #include <assert.h>
  28. #include <fcntl.h>
  29. #include <sys/file.h>
  30. #include <dpkg.h>
  31. #include <dpkg-db.h>
  32. static int dblockfd= -1;
  33. static void cu_unlockdb(int argc, void **argv) {
  34. struct flock fl;
  35. assert(dblockfd >= 0);
  36. fl.l_type= F_UNLCK;
  37. fl.l_whence= SEEK_SET;
  38. fl.l_start= 0;
  39. fl.l_len= 0;
  40. if (fcntl(dblockfd,F_SETLK,&fl) == -1)
  41. ohshite(_("unable to unlock dpkg status database"));
  42. }
  43. void unlockdatabase(const char *admindir) {
  44. pop_cleanup(ehflag_normaltidy); /* calls cu_unlockdb */
  45. }
  46. void lockdatabase(const char *admindir) {
  47. int n;
  48. struct flock fl;
  49. char *dblockfile= NULL;
  50. n= strlen(admindir);
  51. dblockfile= m_malloc(n+sizeof(LOCKFILE)+2);
  52. strcpy(dblockfile,admindir);
  53. strcpy(dblockfile+n, "/" LOCKFILE);
  54. if (dblockfd == -1) {
  55. dblockfd= open(dblockfile, O_RDWR|O_CREAT|O_TRUNC, 0660);
  56. if (dblockfd == -1) {
  57. if (errno == EPERM)
  58. ohshit(_("you do not have permission to lock the dpkg status database"));
  59. ohshite(_("unable to open/create status database lockfile"));
  60. }
  61. }
  62. fl.l_type= F_WRLCK;
  63. fl.l_whence= SEEK_SET;
  64. fl.l_start= 0;
  65. fl.l_len= 0;
  66. if (fcntl(dblockfd,F_SETLK,&fl) == -1) {
  67. if (errno == EACCES || errno == EAGAIN)
  68. ohshit(_("status database area is locked by another process"));
  69. ohshite(_("unable to lock dpkg status database"));
  70. }
  71. setcloexec(dblockfd, dblockfile);
  72. free(dblockfile);
  73. push_cleanup(cu_unlockdb,~0, NULL,0, 0);
  74. }