문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top