-
-
Save altmannmarcelo/4a5c9256a822322ede13e2b75149660e to your computer and use it in GitHub Desktop.
lock file twice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Compile with g++ -o lock lock.cc | |
#include <stdio.h> | |
#include <fcntl.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
int main() | |
{ | |
int fd, fd2 , ret; | |
struct flock strlock; | |
fd = open("testfile", O_CREAT | O_RDWR , 0666 ); | |
if (fd == -1) | |
{ | |
printf("FATAL ERROR: Could not open file\n"); | |
exit(-1); | |
} | |
strlock.l_type = F_WRLCK; | |
strlock.l_whence = SEEK_SET; | |
strlock.l_start = 0L; | |
strlock.l_len = 0L; | |
ret = fcntl (fd, F_SETLK , &strlock); | |
if (ret == -1) | |
{ | |
printf("FATAL ERROR: Could not lock file\n"); | |
exit(-1); | |
} | |
fd2 = open("testfile", O_RDWR , 0666 ); | |
if (fd2 == -1) | |
{ | |
printf("FATAL ERROR: Could not open file\n"); | |
exit(-1); | |
} | |
strlock.l_type = F_WRLCK; | |
strlock.l_whence = SEEK_SET; | |
strlock.l_start = 0L; | |
strlock.l_len = 0L; | |
ret = fcntl (fd2, F_SETLK , &strlock); | |
if (ret == -1) | |
{ | |
printf("FATAL ERROR: Could not lock file\n"); | |
exit(-1); | |
} | |
ret = close( fd ); | |
if (ret == -1) | |
{ | |
printf("FATAL ERROR: Could not close file\n"); | |
exit(-1); | |
} | |
ret = close( fd2 ); | |
if (ret == -1) | |
{ | |
printf("FATAL ERROR: Could not close file\n"); | |
exit(-1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment