Skip to content

Instantly share code, notes, and snippets.

@molpopgen
Last active December 19, 2022 10:03
Show Gist options
  • Save molpopgen/651e4ac81253f34364f7 to your computer and use it in GitHub Desktop.
Save molpopgen/651e4ac81253f34364f7 to your computer and use it in GitHub Desktop.
File locking via boost::interprocess
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <fstream>
int main( int argc, char ** argv )
{
std::ofstream o("monkey.txt",std::ios_base::app);
boost::interprocess::file_lock ol("monkey.txt");
boost::interprocess::scoped_lock<boost::interprocess::file_lock> sol(ol);
while(1){}
}
//Another implementation of block1, but using the lower-level C functions in <fcntl.h>, which work via file descriptors.
#include <fcntl.h>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
int main( int argc, char ** argv )
{
FILE * fp = fopen("monkey.txt","a");
int fd = fileno(fp);
struct flock lock;
lock.l_type = F_WRLCK;/*Write lock*/
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;/*Lock whole file*/
if (fcntl(fd,F_SETLKW,&lock) == -1)
{
std::cerr << "ERROR: could not obtain lock on monkey.txt\n";
std::exit(10);
}
while(1){}
}
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <iostream>
#include <fstream>
int main( int argc, char ** argv )
{
std::ofstream o("monkey.txt",std::ios_base::app);
boost::interprocess::file_lock ol("monkey.txt");
boost::interprocess::scoped_lock<boost::interprocess::file_lock> sol(ol);
std::cerr<<"unlocked\n";
}
//block2, but with C-language API to locking
#include <fcntl.h>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
int main( int argc, char ** argv )
{
FILE * fp = fopen("monkey.txt","a");
int fd = fileno(fp);
struct flock lock;
lock.l_type = F_WRLCK;/*Write lock*/
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;/*Lock whole file*/
if (fcntl(fd,F_SETLKW,&lock) == -1)
{
std::cerr << "ERROR: could not obtain lock on monkey.txt\n";
std::exit(10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment