Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <pwd.h>
- #define GRABBERLOCK "/tmp/grabberlock" /* file used as the lock flag */
- int lock(char *f);
- void unlock(char *f);
- int lock(char *f)
- {
- int fd;
- struct stat statbuf; /* structure used to hold file info */
- if((fd = open(f,O_WRONLY | O_CREAT | O_EXCL, 0644)) == -1)
- /* permission 0644 on lock gives you/group/world of -rw-r--r */
- {
- printf("\nSorry, %s is already locked by ", f);
- stat(f, &statbuf);
- printf("%s\n", getpwuid(statbuf.st_uid)->pw_name);
- return -1;
- }
- else
- {
- close(fd);
- return 0;
- }
- }
- void unlock(char *f)
- { /* invokes a system call which removes the file (effectively just
- removes the link to the file in the directory table). */
- unlink(f);
- }
- int main (int argc, char * const argv[])
- {
- if(lock(GRABBERLOCK) == -1)
- {
- exit(EXIT_FAILURE);
- }
- else
- {
- printf("\nUsing Resouce for 5 Seconds ... \n");
- sleep(5);
- printf("\nDone Using Resource.\n");
- unlock(GRABBERLOCK);
- exit(EXIT_SUCCESS);
- }
- return 0;
- };
Add Comment
Please, Sign In to add comment