A
A
artem782017-04-26 19:23:54
Perl
artem78, 2017-04-26 19:23:54

Non-blocking write to file in Perl?

There is perl code running on Windows that writes data to a file.

use warnings;
use feature 'say';

open(FH, '>', 'file.txt');
$i = 10;
while ($i > 0) {
  say FH $i;
  say $i;
  sleep 1;
  $i--;
}
close(FH)

While writing, another program tries to open the file for reading and fails with the error "IO error 32 - The process cannot access the file because it is being used by another process."
Replacing openwith sysopenwith adding an attribute O_NONBLOCKdoes not work.
use Fcntl qw(O_WRONLY O_CREAT O_APPEND O_NONBLOCK);

sysopen(FH, 'file.txt', O_WRONLY | O_CREAT | O_APPEND | O_NONBLOCK);

Mistake:
Your vendor has not defined Fcntl macro O_NONBLOCK

Using sysopenwithout O_NONBLOCKdoes nothing.
Windows 7, Strawberry Perl 5.16.3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
chorny_cpan, 2017-05-08
@chorny_cpan

Wrote a program that reads this file. She reads this file without problems.

use 5.12.0;use warnings;
use Fcntl qw(:flock);
open(FH, '<', 'file.txt') or die;
flock(FH, LOCK_EX|LOCK_NB) or die "Cannot lock - $! $^E\n";
while (<FH>) {
  print
}

In order for buffering to not work when writing, I added to your program
FH->autoflush(1);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question