1

Reopen voters: flock() doesn't work on named pipes, this is not a dupe.

I was trying to do the following with named pipes:

mkfifo example.txt
( printf "456"; printf "abc"; printf "\n"; ) > example.txt &
( printf "456"; printf "abc"; printf "\n"; ) > example.txt &
( printf "456"; printf "abc"; printf "\n"; ) > example.txt &

If I cat the example.txt sometimes I got:

456abc
456abc
456abc

Other times I got:

456456456abcabc

abc

I was hoping the writes would be atomic. Is there any way to achieve atomic writes?

10
  • 1
    Writes lesser than the page size (nearly always 4096 byte) are atomic. So use printf "456abc\n" and it will be atomic. The answer in the other question, is in your case unusable.
    – peterh
    Oct 13, 2018 at 16:30
  • 1
    The answer in the other question describes using a lockfile, a general solution that is not affected by what the interlocked operations are, whether they be writes to a FIFO or to something else, or indeed whether they even be writes at all. This is, indeed, a duplicate and existing answers at the duplicate address it.
    – JdeBP
    Oct 13, 2018 at 17:10
  • 2
    Why do you say "flock() doesn't work on named pipes"? I just tried it and it seemed to work fine. Oct 13, 2018 at 17:30
  • 1
    Ditto. I believe that I got the accepted answer from the other question to work with a FIFO. You might get more sympathy / support if you posted either an MCVE that demonstrates that it doesn’t work, or a reference that says that it won’t work. (But I doubt that you’ll find the latter, since at least two of us have gotten it to work.) Oct 13, 2018 at 19:13
  • note: your approach to debugging the problem hides some errors .... never repeat the same test data multiple times unless you specifically have repeat the same data ..... use different data in each of the lines (for example: abc123, def456, xyz789)
    – jsotola
    Oct 13, 2018 at 20:10

0

Browse other questions tagged .