I wanted to put a lock while one process is writing on the text file. so no other process can read or write.
Asked
Active
Viewed 789 times
1
-
You could try use [`flock`](https://perldoc.perl.org/functions/flock.html), but it will only work if the other processes also respect the lock – Håkon Hægland Jul 02 '19 at 15:56
-
There is no mandatory file locking on Linux, so you cannot prevent other processes from accessing the file. You can only use cooperative locking, that means all affected processes have to use the same locking mechanism. – Bodo Jul 02 '19 at 15:58
-
Aix or Linux? You have both OSes tagged... – Shawn Jul 02 '19 at 16:52
-
Linux, at least, *kind* of has mandatory file locking, but it requires jumping through a lot of hoops to set up, is all but officially deprecated, and shouldn't be used. – Shawn Jul 02 '19 at 16:57
-
1An alternative is to write to a *temporary* file and then append to the original when your write is done. – David C. Rankin Jul 02 '19 at 22:51
-
Possible duplicate of [Linux flock, how to "just" lock a file?](https://stackoverflow.com/questions/24388009/linux-flock-how-to-just-lock-a-file) – syam Jul 03 '19 at 06:44
-
@Shawn it's for both AIX and linux – Balaji Dongare Jul 03 '19 at 14:36
1 Answers
3
The flock
file locking mechanism in Perl is advisory. It can be used to exclude other processes from accessing a file if those other processes are also using flock. Even this mechanism will be flaky with some systems (I'm looking at you, NFS).
It may be more reliable to operate with an anonymous, temporary file that other processes will not know about, and to rename your file when you are done with it.
use File::Temp;
my ($fh, $obscure_filename) = tempfile();
print $fh "some data ...\n";
...
close $fh;
rename($obscure_filename, $the_real_name_of_the_file);

mob
- 117,087
- 18
- 149
- 283