I’m sending data from one process to another pipe
and I want to clear the pipe
after reading.
Is there a function in C
that can do this ?
Advertisement
Answer
Yes. It’s just the read
function offered by the stdio
library. You have to invoke it as many times as you need in order to be sure the pipe will be empty.
As the documentation suggests, the read
function attempts reading count
bytes from an I/O channel (a pipe in your case) for which you have passed the file descriptor as first argument, and places its content into a buffer with enough room to accommodate it.
Let’s recall that the read
function may return a value indicating a number of bytes read that is smaller than that of those requested. This is perfectly fine if there are less bytes to read than what you expected.
Also remeber that reading from a pipe is blocking if there’s nothing to read and the writer has not yet closed the relative descriptor, thus meaning that you’ll not get EOF until the counterpart closes its descriptor. Therefore you’ll stuck while attempting to read from pipe. If you are intended to avoid the aforementioned possibility I suggest to follow the solution below based on the poll
function to verify whether there’s data to read from a file descriptor:
#include <poll.h> struct pollfd pfd; int main(void) { /* your operations */ pfd.fd = pipe_fd; pfd.events = POLLIN; while (poll(&pfd, 1, 0) == 1) { /* there's available data, read it */ } return 0; }