Recently, I encountered a problem because I was working on php. I used the following code to lock a file handle [php] & lt ;? Php $ filename = & quot;/tmp/lock.txt & quot; $ fp = fopen ($ filename, & quot; r + & quot;); if (! $ Fp) {die (& quot; openfail
Recently, I encountered a problem because I was working on php. I used the following code to lock a file handle.
[Php]
$ Filename = "/tmp/lock.txt ";
$ Fp = fopen ($ filename, "r + ");
If (! $ Fp ){
Die ("open failed .");
}
If (flock ($ fp, LOCK_EX) {// sort it to lock
Sleep (20 );
$ Count = (int) fgets ($ fp );
$ Count + = 1;
Fseek ($ fp, 0 );
Fwrite ($ fp, (string) $ count );
Fflush ($ fp); // flush output before releasing the lock
Flock ($ fp, LOCK_UN); // release lock
} Else {
Echo "Couldn't get the lock! ";
}
Fclose ($ fp );
?>
$ Filename = "/tmp/lock.txt ";
$ Fp = fopen ($ filename, "r + ");
If (! $ Fp ){
Die ("open failed .");
}
If (flock ($ fp, LOCK_EX) {// sort it to lock
Sleep (20 );
$ Count = (int) fgets ($ fp );
$ Count + = 1;
Fseek ($ fp, 0 );
Fwrite ($ fp, (string) $ count );
Fflush ($ fp); // flush output before releasing the lock
Flock ($ fp, LOCK_UN); // release lock
} Else {
Echo "Couldn't get the lock! ";
}
Fclose ($ fp );
?>
Then, try to use vi to edit/tmp/lock.txt within 20 seconds of sleep, and find that the file content can be modified successfully without waiting for the end of the first script. After pondering the document, we found that there is a concept called "consultation file lock", that is, all access programs must be locked in the same way to take effect, otherwise it will not work.
Try to use the following code for access within 20 seconds:
[Php]
$ Filename = "/tmp/lock.txt ";
$ Fp = fopen ($ filename, "r + ");
If (! $ Fp ){
Die ("open failed .");
}
If (flock ($ fp, LOCK_EX) {// sort it to lock
$ Count = (int) fgets ($ fp );
Echo $ count;
$ Count + = 1;
Flock ($ fp, LOCK_UN); // release lock
} Else {
Echo "Couldn't get the lock! ";
}
Fclose ($ fp );
?>
$ Filename = "/tmp/lock.txt ";
$ Fp = fopen ($ filename, "r + ");
If (! $ Fp ){
Die ("open failed .");
}
If (flock ($ fp, LOCK_EX) {// sort it to lock
$ Count = (int) fgets ($ fp );
Echo $ count;
$ Count + = 1;
Flock ($ fp, LOCK_UN); // release lock
} Else {
Echo "Couldn't get the lock! ";
}
Fclose ($ fp );
?>
The blocking was found to be successful (the second script needs to wait until the first script ends to continue running ).
So what is locking in the same way?
Group:
1. try to change the flock parameter of script 1 to LOCK_SH, script 2 remains unchanged, and the test finds that the blocking is still successful;
2. modify the flock parameters of script 1 and script 2 to LOCK_SH. it is found that script 2 can return results without waiting for script 1 to finish running;
Group B:
1. try to change the fopen parameter of script 2 to "r", which is the same as Group;
Group C:
1. try to change the flock parameter of script 2 to LOCK_SH, and script 1 remains unchanged.