Question

I have some child processes which should write some logs into a common file. I am wondering if this code work so that the processes will write into the common file without collisions:

sub appendLogs {
    open FILE, "+>>", $DMP or die "$!";
    flock FILE, LOCK_EX or die "$!";
    print FILE "xyz\n";
    close FILE;
}

If not, could you give me any hints, how I could fix or improve it?

Was it helpful?

Solution

Yes, as long as every process that tries to write to file uses flock, they will go without collisions.

OTHER TIPS

For logging purpose, I would use Log4perl instead of reinventing the wheel. It has a support for what you are looking.

If you would like your code to be portable, you should seek to the end of the file after you lock the filehandle but before you write to it. See the "mailbox appender" example in perldoc -f flock, which is similar to what you are doing.

sub appendLogs {
    open FILE, "+>>", $DMP or die "$!";
    flock FILE, LOCK_EX or die "$!";
    seek FILE, 0, 2;       # <--- after lock, move cursor to end of file
    print FILE "xyz\n";
    close FILE;
}

The seek may be necessary because another process could append the file (and move the position of the end of the file) after you open the file handle but before you acquire the lock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top