mod_perl fun

grantm on 2003-08-04T09:52:59

A colleague asked me to help him debug a bit of code (running under mod_perl) that looked something like this:

open TEST, ">$filepath";

print TEST "A test message\n";

His symptom was that the file would get created but nothing would get written to it - usually. Sometimes "inexplicably" something would get written but there was "no pattern" to when it worked and when it didn't.

Ignoring for a moment the capital offense of failing to check the return value from open (which was fine as it happens) and the fact that he ought to be using the three argument open ($filepath was trusted in this case), can you see the problem?

 

 

 

 

 

 

 

 

 

He forgot to close the file, so the one line output from print stayed in the buffer. Since he was using a global filehandle it never went out of scope and since it was running under mod_perl, the Perl interpreter never exited so Perl never closed it for him. If he had run it repeatedly, each open would have caused an implicit close and buffer flush but since he kept making 'random changes' he was never quite sure what made it work.


IO::File

Dom2 on 2003-08-04T11:25:40

This is one of the reasons why I try to use IO::File for everything. It just makes life much easier.

Of course, I then come a across a problem with implicit closes, so I really should call close explicitly anyway...

-Dom

Re:IO::File

koschei on 2003-08-07T15:04:50

Since 5.6 you haven't even needed IO::File.
  open my $fh, '>', $filepath or die "Could not open $filepath: $!\n";
It's great and it's built in.

(And, hopefully, my example will show the other flaw in the program - no error handling.)

Looks to me...

phillup on 2003-08-04T20:57:30

Looks to me like the file gets created every time... instead of appended.

Then... he is running it (I assume. Bad me!) under Apache, which spawns multiple children.

Then... the first child creates the file and writes to it. Then... who knows which kid gets to run the program the next time... but, when the kid runs the program... it wipes out the existing file and starts anew.

This looks to me like someone forgot that the code will be running multiple times, simultaneously.

mod_perl, so...

bart on 2003-08-04T21:24:31

The file never gets closed? The string stays in the buffer and never gets written to disk?

I guess that's what Dom2 is saying, too.