Correct file handling on Linux

J

Jon

Lately I have been reviewing how my Perl scripts handles files they
write to, as until now I have already taken for granted that it will
"just work", so many of my scripts never stopped when they could not
write to or read a file.

My normal setup is Perl 5.6.0, Linux 2.4.x kernel, ext2 filesystem
(although our newer servers do use ext3, however unfortunately most
still use ext2).

open(LOG,">>/path/to/file") or &bad_file;
print LOG "xx";
close(LOG);

Now that works fine, and if the path is invalid it will error out
nicely, however, one of my scripts has the possibility of being run
regularly, each time it will write to a file.

So my question is, if 2 scripts run at the same split second and get
around to writing to the same file at the same time what would be the
result? Would one fail and the other succeed, or would the file be
damaged maybe (if I was using the above code for example).

Thank you for any advise,

Jon.
 
T

Tad McClellan

Jon said:
So my question is, if 2 scripts run at the same split second and get


That is known as a "race condition" in computer science lingo.

around to writing to the same file at the same time what would be the
result?


Bad, because...

Would one fail and the other succeed, or would the file be
damaged maybe (if I was using the above code for example).


.... it could be any of those, in general.

Thank you for any advise,


To avoid corrupting data due to a race condition, you must
implement some form of "file locking" in *each* program
that might write to the common file.

There are several Perl FAQs about file locking:

perldoc -q "\block"

(or put the data in a real RDBMS, and it can do the locking for you)
 
P

Pierre Asselin

Jon said:
So my question is, if 2 scripts run at the same split second and get
around to writing to the same file at the same time what would be the
result?

In general, the file will contain erratic bursts of data both
programs, unless you write the code carefully. For log files, you
should
1) open the file in append mode,
2) use syswrite() exclusively.

open(LOG, '>>the_log_file');
...
syswrite LOG, "Complete, uninterrupted line.\n"
...
close(LOG);
 

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
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top