woytekm woytekm - 1 year ago 188
C Question

How to flush a pipe created by pipe() on Linux?

I want to flush a pipe created by pipe() call on Linux, as i am interested only in data that will come after read() was called. I am trying following ioctl call:

ioctl_err = ioctl(G_MIDI_inout_event_pipe[0],I_FLUSH,FLUSHR);

But ioctl returns ENOTTY and pipe is not flushed.
How to properly flush such stream?

Answer Source

There isn't a standard way to do it.

You could consider setting the non-blocking attribute on the pipe followed by a preliminary read() to clear the data, then reset the attribute to blocking before collecting the data you're really after. You'd have to attempt to read at least the pipe size — which can be as small as 4 KiB or can be much larger (64 KiB on Linux, IIRC). That's kinda fiddly, but it would 'work' with a minimal window of time between TOCTOU (time of check, time of use) — basically, the two read calls I'm postulating. That shouldn't matter to you; it was data written after the start of the reading process.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download