2

This is at risk of being an excessively broad/subjective question, so I'll try to make it as specific as possible.

I'm currently learning how to use pipes properly. Often in code I've reviewed, after creating a pipe with pipe(my $pipe_reader, my $pipe_writer);, somebody will call $pipe_writer->autoflush(1);.

That isn't a requirement to use "whenever you use pipes", correct? You would just use it when you want to make sure the reader gets the data immediately after the writer writes it?

Stephen
  • 8,508
  • 12
  • 56
  • 96

1 Answers1

6

Correct. If you don't turn on autoflush, everything will still work fine, except that the write buffer will only be flushed when it fills up, or when you close the pipe, instead of immediately on every write. If you're sending bulk data over the pipe then you can leave it off; if you're doing anything "interactive" then you probably want it on.

In particular, if you're writing to and reading from a child process, it's easy for buffering to lead to a deadlock situation, as follows: you send a request to the child process, and then read a response from it. Without buffering, this works okay. But with buffering, the child doesn't see the request because it's still waiting in your output buffer, so it doesn't produce a response, so your read never unblocks, and nothing ever happens. Enabling autoflush, or doing a manual flush after each complete request before switching to reading, avoids this problem.

You can also avoid output buffering by using syswrite, but don't mix syswrite and print; since syswrite bypasses print's buffers, you can end up with output going out in a different order from what you expected!

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • 3
    Writing to the pipe exclusively with `syswrite` also bypasses buffered I/O and makes `autoflush` unnecessary. – mob Feb 02 '18 at 22:22
  • 2
    The deadlock can also happen when trying to write to a full pipe buffer. See [Deadlocks due to buffering. How does it work?](https://stackoverflow.com/q/40189625/2173773) – Håkon Hægland Feb 03 '18 at 05:46