showlocks.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. ** This file implements a simple command-line utility that shows all of the
  3. ** Posix Advisory Locks on a file.
  4. **
  5. ** Usage:
  6. **
  7. ** showlocks FILENAME
  8. **
  9. ** To compile: gcc -o showlocks showlocks.c
  10. */
  11. #include <stdio.h>
  12. #include <unistd.h>
  13. #include <fcntl.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. /* This utility only looks for locks in the first 2 billion bytes */
  17. #define MX_LCK 2147483647
  18. /*
  19. ** Print all locks on the inode of "fd" that occur in between
  20. ** lwr and upr, inclusive.
  21. */
  22. static int showLocksInRange(int fd, off_t lwr, off_t upr){
  23. int cnt = 0;
  24. struct flock x;
  25. struct lockRange {
  26. off_t lwr;
  27. off_t upr;
  28. } *aPending = 0;
  29. int nAlloc = 1;
  30. int nPending = 0;
  31. int nDone = 0;
  32. nPending = 1;
  33. aPending = malloc( sizeof(aPending[0]) );
  34. if( aPending==0 ){
  35. fprintf(stderr, "out of memory\n");
  36. exit(1);
  37. }
  38. aPending[0].lwr = lwr;
  39. aPending[0].upr = upr;
  40. for(nDone=0; nDone<nPending; nDone++){
  41. lwr = aPending[nDone].lwr;
  42. upr = aPending[nDone].upr;
  43. if( lwr>=upr ) continue;
  44. x.l_type = F_WRLCK;
  45. x.l_whence = SEEK_SET;
  46. x.l_start = lwr;
  47. x.l_len = upr - lwr;
  48. fcntl(fd, F_GETLK, &x);
  49. if( x.l_type==F_UNLCK ) continue;
  50. printf("start: %-12d len: %-5d pid: %-5d type: %s\n",
  51. (int)x.l_start, (int)x.l_len,
  52. x.l_pid, x.l_type==F_WRLCK ? "WRLCK" : "RDLCK");
  53. cnt++;
  54. if( nPending+2 > nAlloc ){
  55. nAlloc = nAlloc*2 + 2;
  56. aPending = realloc(aPending, sizeof(aPending[0])*nAlloc );
  57. }
  58. if( aPending==0 ){
  59. fprintf(stderr, "unable to realloc for %d bytes\n",
  60. (int)sizeof(aPending[0])*(nPending+2));
  61. exit(1);
  62. }
  63. if( lwr<x.l_start ){
  64. aPending[nPending].lwr = lwr;
  65. aPending[nPending].upr = x.l_start;
  66. nPending++;
  67. }
  68. if( x.l_start+x.l_len<=upr ){
  69. aPending[nPending].lwr = x.l_start + x.l_len;
  70. aPending[nPending].upr = upr;
  71. nPending++;
  72. }
  73. }
  74. free(aPending);
  75. return cnt;
  76. }
  77. int main(int argc, char **argv){
  78. int fd;
  79. int cnt;
  80. if( argc!=2 ){
  81. fprintf(stderr, "Usage: %s FILENAME\n", argv[0]);
  82. return 1;
  83. }
  84. fd = open(argv[1], O_RDWR, 0);
  85. if( fd<0 ){
  86. fprintf(stderr, "%s: cannot open %s\n", argv[0], argv[1]);
  87. return 1;
  88. }
  89. cnt = showLocksInRange(fd, 0, MX_LCK);
  90. if( cnt==0 ) printf("no locks\n");
  91. close(fd);
  92. return 0;
  93. }