There are two types of file locks: shared and exclusive, that is, read lock (LOCK_SH) and write lock (LOCK_EX)
File locks are typically used in this way:
$fp = fopen ("filename", "a"); Flock ($FP, lock_sh) or Die ("LOCK error") $str = Fread ($fp, 1024x768); Flock ($FP, lock_un); Fclose ($FP);
Note that after fwrite, the file is updated immediately, instead of waiting for fwrite and then fclose after the file is updated, this can be checked by reading this file before fclose after fwrite
But when to use LOCK_EX when to use Lock_sh?
When reading:
If you do not want dirty data to appear, it is best to use lock_sh shared locks. Here are three things to consider:
1. If the reader does not have a shared lock, then other programs to write (whether the write is locking or unlocked) will immediately write success. If you just read half of it and then write it to another program, then half of the reading is probably half right (the first half is a modified one and the last half is a modified one).
2. If you add a shared lock when reading (because it is just read, there is no need to use an exclusive lock), this time, the other program began to write, the program does not use the lock, then write the program will directly modify the file, will also lead to the same problem
3. Ideally, when reading locking (LOCK_SH), when writing also to lock (LOCK_EX), so that the program will wait until the completion of the program before the operation, without any hasty operation of the situation
When writing:
If multiple write programs do not lock the file at the same time, then the final data may be part of a program written, part of the B program is written
If it was locked when it was written, and there were other programs to read, what would he read?
1. If the reader does not request a shared lock, he will read the dirty data. For example, write a program to write a,b,c three parts, write a, this time read a, continue to write B, at this time read the AB, and then write C, this time read ABC.
2. If the reader has previously applied for a shared lock, the read program will wait until the program writes out the ABC and releases the lock before reading.