Previous operations on files were usually done in one process, and the same file was recently required to be operated on in two processes. So I thought of the file lock. Linux can use the flock () function to unlock files and other operations. A brief introduction to the Flock () Function: Table header file #include
Defines the function int flock (int fd,int operation);
The function description flock () does various locking or unlocking of the file referred to by the parameter FD according to the method specified by the parameter operation. This function can only lock the entire file and cannot lock a region of the file.
Parameter operation has the following four scenarios:
Lock_sh establish a shared lock. Multiple processes can share a lock on the same file at the same time.
LOCK_EX establishes a mutex lock. A file has only one mutex lock at a time.
Lock_un the file lock state.
LOCK_NB cannot establish a lock, this operation is not blocked and immediately returns to the process. Usually done with lock_sh or lock_ex or (|) Combination.
A single file cannot establish both shared and mutex locks at the same time, and file descriptors do not inherit such locks when using DUP () or fork ().
A return value of 0 indicates success, and if any error returns-1, the error code is stored in errno.
For better portability, I chose the combination of fopen and fclose for file opening and closing, but the first parameter of flock required a file descriptor of type int. This converts the file pointer returned by fopen to a file descriptor of type int (assuming the file descriptor returned by the Open function is FD, and fopen returns a file pointer of *FP, FD is equivalent to Fp->_fileno).
The following are examples of two processes:
#include
#include
#include
#include
int main (void)
{
FILE *FP = NULL;
int i = 20;
if (fp = fopen ("./file_lock.test", "r+b")) = = NULL)//Open File
printf ("File Open error!\n");
if (Flock (Fp->_fileno, LOCK_EX)!= 0)//Lock the file
printf ("File lock by others\n");
while (1)//Enter the loop, lock time is 20 seconds, print Countdown
{
printf ("%d\n", i--);
Sleep (1);
if (i = = 0)
Break
}
Fclose (FP); Exit after 20 seconds, close file
Flock (Fp->_fileno, lock_un); File unlock
return 0;
}
#include
#include
#include
#include
int main (void)
{
FILE *FP = NULL;
int i = 0;
if (fp = fopen ("./file_lock.test", "r+b")) = = NULL)//Open File
printf ("File Open error!\n");
Flock (Fp->_fileno, LOCK_EX); File plus lock
while (1)//Into the loop
{
printf ("%d\n", i++);
Sleep (1);
}
Fclose (FP); Close File
Flock (Fp->_fileno, lock_un); Release file lock
return 0;
}
Run file1.c first, then run file2.c (run file1.c after 20 seconds to run file2.c otherwise do not see the phenomenon) is: file1.c execution up after, start Countdown. Running file2.c at this time will block at the lock place. When the file1.c is run for 20 seconds and the file is closed and the file lock is released, FILE2.C starts running.