lock_fcntl.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* include my_lock_init */
  2. #include "unp.h"
  3. static struct flock lock_it, unlock_it;
  4. static int lock_fd = -1;
  5. /* fcntl() will fail if my_lock_init() not called */
  6. void
  7. my_lock_init(char *pathname)
  8. {
  9. char lock_file[1024];
  10. /* 4must copy caller's string, in case it's a constant */
  11. strncpy(lock_file, pathname, sizeof(lock_file));
  12. lock_fd = Mkstemp(lock_file);
  13. Unlink(lock_file); /* but lock_fd remains open */
  14. lock_it.l_type = F_WRLCK;
  15. lock_it.l_whence = SEEK_SET;
  16. lock_it.l_start = 0;
  17. lock_it.l_len = 0;
  18. unlock_it.l_type = F_UNLCK;
  19. unlock_it.l_whence = SEEK_SET;
  20. unlock_it.l_start = 0;
  21. unlock_it.l_len = 0;
  22. }
  23. /* end my_lock_init */
  24. /* include my_lock_wait */
  25. void
  26. my_lock_wait()
  27. {
  28. int rc;
  29. while ( (rc = fcntl(lock_fd, F_SETLKW, &lock_it)) < 0) {
  30. if (errno == EINTR)
  31. continue;
  32. else
  33. err_sys("fcntl error for my_lock_wait");
  34. }
  35. }
  36. void
  37. my_lock_release()
  38. {
  39. if (fcntl(lock_fd, F_SETLKW, &unlock_it) < 0)
  40. err_sys("fcntl error for my_lock_release");
  41. }
  42. /* end my_lock_wait */