test-lock.c 687 B

123456789101112131415161718192021222324252627282930
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <fcntl.h>
  4. #include <errno.h>
  5. int main(int argc, char * argv[]) {
  6. if (argc < 2 ){
  7. fprintf(stderr, "usage: test-lock LOCKPATH\n");
  8. return 1;
  9. }
  10. int fd = open(argv[1],O_RDWR|O_CREAT|O_EXCL);
  11. if (fd < 0) {
  12. if (errno == EEXIST) {
  13. fprintf(stderr, "Lock is already held.\n");
  14. return 0;
  15. } else {
  16. fprintf(stderr, "Some other error? %d = %s\n", errno, strerror(errno));
  17. return 1;
  18. }
  19. } else {
  20. fprintf(stderr, "I have the lock, the fd is %d.\n", fd);
  21. fprintf(stderr, "Press Enter to release lock.\n");
  22. while (!feof(stdin) && fgetc(stdin) != '\n') {
  23. /* nothing */
  24. }
  25. close(fd);
  26. unlink(argv[1]);
  27. return 0;
  28. }
  29. }