简体   繁体   中英

What is the best way to consume data from a pipe?

I'm interested in the more portable yet fastest way to consume data from a pipe.

For example, in linux the fastest way I can think of is the following:

#define _GNU_SOURCE
/* ... */
int fd;
int pipefd[2];

pipe(pipefd);

/* ... */
fd = open("/dev/null", O_WRONLY);
splice(pipefd[0], NULL, fd, NULL, INT_MAX, SPLICE_F_MOVE);

... but it's not portable.

UPDATE 1:

What if I close the entire pipe and create one each time I need it?

/*consume*/
close(pipefd[0]);
close(pipefd[1]);

would it be faster than using other methods, ie read()/write()?

Are you sure that this operation is performance critical to your program? If not, just use the simplest thing that works, probably something along the lines cat the_pipe > /dev/null or its equivalent in C, a loop read(2)ing a block of data (say 4KiB, or perhaps get an "optimal" size, on current Linux the maximal data in a pipe is 64KiB; take a look at pipe(7)). Perhaps it is easier to shut up the producer of the data instead of getting it only to throw it away? In performance terms, that just can't be beat...

Use the read function. Refer to the man pages here - http://linux.die.net/man/3/read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM