Skip to content

Instantly share code, notes, and snippets.

@altmannmarcelo
Created April 26, 2023 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save altmannmarcelo/4a5c9256a822322ede13e2b75149660e to your computer and use it in GitHub Desktop.
Save altmannmarcelo/4a5c9256a822322ede13e2b75149660e to your computer and use it in GitHub Desktop.
lock file twice
# 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