Is it needed to lock open file for write?

N

news.t-com.hr

Is it needed to lock open file for write?

use Fcntl qw:)flock);
open(FH, ">codes.txt") or die "can't open codes.txt $!";
flock(FH, LOCK_EX) or die "can't flock codes.txt $!";

Or is also good only to use command open

open(FH, ">codes.txt") or die "can't open codes.txt $!";


TNX
 
I

it_says_BALLS_on_your forehead

news.t-com.hr said:
Is it needed to lock open file for write?

use Fcntl qw:)flock);
open(FH, ">codes.txt") or die "can't open codes.txt $!";
flock(FH, LOCK_EX) or die "can't flock codes.txt $!";

Or is also good only to use command open

open(FH, ">codes.txt") or die "can't open codes.txt $!";

AFAIK, locking is really only necessary if there is a possibility of
two processes operating on the same file at the same time--in your case
the operation would be a file write.
 
R

Rhugga

The only problem with file locking is that not all utilities/commands
honor file locking.

For example, let's say your perl program is running and has an
exlcusive lock on /etc/password.

Then let's say, for example, that yppasswd doesn't honor exclusive
locks, and just does it's thing regardless. The user jsmith decides to
change his password while your program is doing it's thing. You now run
into the risk of 1) corrupting the file completely or 2) losing your
changes to the file, or 3) the user's password change being lost.

You'd be surprised at the number of standard commands that don't honor
exclusive locks. I think these commands are become more rare, but all
it takes is 1 to make things go pear shaped. For Solaris, somewhere on
bigadmin or sunsolve there is a list of commands and/or libraries that
fall into this category. I think the list has been decreasing over the
years but I'm sure there are still some.

This is one reason why its recommended when tweaking /etc/passwd or
/etc/shadow from a script that you make a copy of the file, modify the
copy, the move the modifed copy into place. (even this has its risks
but they are very minimized)

In your case, however, if your code will be the only one ever modifying
the file, and your locking just to prevent 2+ running copies from
stepping on each other, than it would work for you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top