Inter process synchronization (Linux)

Synchronizes the access on critical sections between processes.


Prototypic lock file (with symlink)

#include <string>

class LockFile
{
public:
  LockFile(std::string& fpath);
  ~LockFile();
 
private:
  void lock();
  void unlock();
 
  std::string m_fpath;
};
#include "lockfile.hpp"
#include <unistd.h>
 
LockFile::LockFile(std::string& fpath) : m_fpath(fpath)
{
  lock();
}
 
LockFile::~LockFile()
{
  unlock();
}
 
void LockFile::lock()
{
  std::string pid = std::to_string(getpid());
  while (symlink(pid.c_str(), m_fpath.c_str()))
  {
    usleep(500000);
  }
}
 
void LockFile::unlock()
{
  unlink(m_fpath.c_str());
}
#include "lockfile.hpp"
#include <string>
 
int main()
{
  std::string fpath("/tmp/lock_file");
  LockFile lockfile(fpath);
  // do synchronized stuff
  return 0;
}

Alternative

Boost has an interprocess namespace which provides for example a mutex in shared memory.