Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

PerlIO, random write file access and O_CREAT

by vsespb (Chaplain)
on May 29, 2013 at 15:06 UTC ( #1035861=perlquestion: print w/replies, xml ) Need Help??
vsespb has asked for the wisdom of the Perl Monks concerning the following question:

I want to peform multiple writes to a file, from different processes, at the same time. Writes will be at different, non-overlapping positions. I want to use perlio for this (to avoid coding workarounds when syswrite is not writing all data). And the file to write data, might not exsit before write.

So, I found this is pretty complicated. Perl open modes maps to fopen() fopen

And it does not have mode with O_CREAT, but without O_TRUNC/O_APPEND

Obviously I cannot use O_TRUNC because it will destroy file content, and cannot use O_APPEND because I cannot use seek with it.

possible workaround is only use

open my $f, "+>>", $filename; close $f; open $f, '+<';

This will create file if it's not exists, and will open it in read-write mode. (I assume there will be no race-conditions between close and second open, such race condition can be worked around if I check errno after last open and put it into while loop)

Question: Am I missing something? It there easier way? Or maybe better avoid perl IO for such task (i.e. above code contain bugs) ?

Replies are listed 'Best First'.
Re: PerlIO, random write file access and O_CREAT (sysopen)
by tye (Sage) on May 29, 2013 at 15:37 UTC

    There is sysopen:

    use Fcntl qw< O_CREAT O_RDWR >; sysopen my $fh, $filename, O_CREAT()|O_RDWR(), 0666 or die "Can't open $filename: $!\n";

    (Note that your code still unconditionally truncates the file each time.)

    - tye        

      I thought sysopen can't be mixes with print/read, as buffered IO and unbuffered cannot be mixed? And I mentioned that I don't want to use syswrite

      Or sysopen is not about unbuffered IO (in opposite to syswrite) ?

      (Note that your code still unconditionally truncates the file each time.)
      Ok, could you please example why? First file open mode is append, and second is read (read/write)

        Oh, right, the append prevents the truncate. My mistake.

        sysopen is just a different way of getting a file handle. It has no bearing on whether you use buffered or unbuffered I/O with that handle.

        - tye        

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1035861]
Approved by toolic
Front-paged by toolic
[marto]: good morning all
[Corion]: Hi marto!

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2018-05-24 07:18 GMT
Find Nodes?
    Voting Booth?