#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main (int argc,char* argv[])
{
int FD;
int Lock_result;
struct flock lock;
char * pfilename = "Tmp.lck";
FD = open (PFILENAME,O_RDWR);
if (fd<0)
{
printf ("Open file failed.\n");
return 1;
}
Lock_result = LOCKF (fd,f_test,0); Parameter uses F_lock, if it is already locked, it blocks until the previous process releases the lock, and the parameter 0 indicates that the entire file is locked
Return 0 means unlocked or locked by the current process; 1 indicates lock by other process
if (lock_result<0)
{
Perror ("Exec lockf function failed.\n");
return 1;
}
Lock_result = LOCKF (fd,f_lock,0); Parameter uses F_lock, if it is already locked, it blocks until the previous process releases the lock, and the parameter 0 indicates that the entire file is locked
if (lock_result<0)
{
Perror ("Exec lockf function failed.\n");
return 1;
}
printf ("Pid:%ld process locked The file.\n", (long) getpid ());
Do something
while (GetChar () <0);
printf ("Pid:%ld Process Release The file.\n", (long) getpid ());
return 0;
}
(GO) Linux with file lock implementation to ensure that a program can only start a process