HOW TO CREATE LOCK FILE IN C

 

File locking provides a very simple yet incredibly useful mechanism for coordinating file accesses. Before I begin to lay out the details, let me fill you in on some file locking secrets:-

There are two types of locking mechanisms: mandatory and advisory.

– Mandatory systems will actually prevent read() and write() to file.

– There are two types of (advisory!) locks: read locks and write locks (also referred to as shared locks and exclusive locks, respectively.)

 

Here I am demonstrating READ-LOCK …

In  my  case , I want  to reduce CPU usage which  takes very  high CPU usage % in case of accessing Sqlite3  by  two  application simultaneously.

To solve  this problem  I  applied  lock  file  concept  to synchronizes  applications ,

I applied it for three different applications.

 

Steps followed while creating lock file:-

 

– Finalize  File Name (xyz.lock)

– Finalize  lock file  location

– Before running  application , check lock file is  present or not

if(getlock(lockfile)== 1) :: Lock file is not present

– If lock file is not present  then create  lock file

int lockstatus = setlock(lockfile);

– After  completion  of job  delete lock file

 

Removelock (lockfile)

– If  lock file is  present  then sleep  for  sometime then again check for lock file

– While creating lock file, handle unexpected application closing mechanism to avoid trouble when next time application needs to be run.

 

Note: Extension of lock file is (abc.lock)

Note: Remove lock file when application is forcefully terminating (ctrl + C)

 

(Example of lock file in c using semaphores : –  )

Reference: http://www.c-program-example.com/2012/04/c-program-to-lock-file-using-semaphores.html