how exactly does the constant "PIPE_BUF" defined in limits.h work in linux. And when I use it as "count" in the system call "read(int fd, void *buf, size_t count);", does the system call "read", return one byte at a time and waits till it reaches the end of file? The code below takes two commands "last" and "sort" and makes two popen calls. Like ~$foo last sort In the code below I did not understand why the while loop was necessary if the read returns all available bytes only once. And also, how does the write to the popen understands that all input have been received and now it's time for the popen to execute the program.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
int main (int argc, char* argv[])
{
FILE *fin, *fout;
char buffer[PIPE_BUF];
int n;
if (argc < 3)
{
printf("Need two parameters.\n");
exit(1);
}
fin=popen(argv[1], "r");
fout=popen(argv[2],"w");
fflush(fout);
while ((n=read(fileno(fin), buffer, PIPE_BUF)) > 0)
{
write(fileno(fout), buffer, n);
}
pclose(fin);
pclose(fout);
return 0;
}