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 synchronies 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
è 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 : – )