Guest User

Untitled

a guest
May 26th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <fcntl.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <pwd.h>
  9.  
  10. #define GRABBERLOCK "/tmp/grabberlock" /* file used as the lock flag */
  11.  
  12. int lock(char *f);
  13. void unlock(char *f);
  14.  
  15. int lock(char *f)
  16. {
  17. int fd;
  18. struct stat statbuf; /* structure used to hold file info */
  19.  
  20. if((fd = open(f,O_WRONLY | O_CREAT | O_EXCL, 0644)) == -1)
  21.  
  22. /* permission 0644 on lock gives you/group/world of -rw-r--r */
  23. {
  24. printf("\nSorry, %s is already locked by ", f);
  25. stat(f, &statbuf);
  26. printf("%s\n", getpwuid(statbuf.st_uid)->pw_name);
  27. return -1;
  28. }
  29. else
  30. {
  31. close(fd);
  32. return 0;
  33. }
  34. }
  35.  
  36. void unlock(char *f)
  37. { /* invokes a system call which removes the file (effectively just
  38. removes the link to the file in the directory table). */
  39. unlink(f);
  40. }
  41.  
  42. int main (int argc, char * const argv[])
  43. {
  44. if(lock(GRABBERLOCK) == -1)
  45. {
  46. exit(EXIT_FAILURE);
  47. }
  48. else
  49. {
  50. printf("\nUsing Resouce for 5 Seconds ... \n");
  51. sleep(5);
  52. printf("\nDone Using Resource.\n");
  53. unlock(GRABBERLOCK);
  54. exit(EXIT_SUCCESS);
  55. }
  56. return 0;
  57. };
Add Comment
Please, Sign In to add comment