chilukuri_perl has asked for the wisdom of the Perl Monks concerning the following question:

There are two scripts.
script2.pl is called from script1.pl
Both scripts write to same file 'xyz.log'. script2.pl opens with append mode.
Script1.pl ---------- #!/usr/local/bin/perl $logFl = "xyz.log"; open (FIRSTFH, "> $logFl") || die "couldn't open file...$!\n"; print FIRSTFH "This is from first script\n"; system("script2.pl $logFl"); #print FIRSTFH "This is second print in first script\n"; Script2.pl ---------- #!/usr/local/bin/perl $logFl2 = "xyz.log"; open (FIRSTFH, ">> $logFl2") || die "couldn't open file in script2...$ +!\n"; print FIRSTFH "This is from second script\n";
Running above script1.pl will result with following file.
$ cat xyz.log
This is from first script
This is from second script

But if commented line
#print FIRSTFH "This is second print in first script\n";
is uncommented and ran then following will be the result.
$ cat xyz.log
This is from first script
This is second print in first script

Please let me know how to make script1.pl work so that all messages are in order in output file. That is it should contain three messages
This is from first script
This is from second script
This is second print in first script
Thanks

Replies are listed 'Best First'.
Re: File content written by script and a called script
by moritz (Cardinal) on Sep 23, 2009 at 11:05 UTC
    You could try to seek the end of file after the second script has been called.
    Perl 6 - links to (nearly) everything that is Perl 6.
      Adding seek doesn't solve it.
      #!/usr/local/bin/perl $logFl = "xyz.log"; open (FIRSTFH, "> $logFl") || die "couldn't open file...$!\n"; print FIRSTFH "This is from first script\n"; system("script2.pl $logFl"); seek (FIRSTFH, 0, SEEK_END); print FIRSTFH "This is second print in first script\n"; ~
      Now output is
      $ cat xyz.log
      This is second print in first script
      m second script

      Note that some part of print message in second script is not printed
        Adding seek in second script solved it. Thanks...
Re: File content written by script and a called script
by vitoco (Hermit) on Sep 23, 2009 at 13:35 UTC

    There is a race condition. seeking the end of file is not enough, you also need to flock the log file.