Hi,
I have been learning about pipes in C recently. Here is an example of some code that works fine:
Code:
// some lines are omitted
switch(fork()) {
case -1:
perror("Fork");
exit(1);
case 0:
dup2(p[1], fileno(stdout));
close(p[0]);
close(p[1]);
execl("/usr/bin/last", "last", 0);
_exit(0);
default:
printf("parent\n");
dup2(p[0], fileno(stdin));
close(p[1]);
close(p[0]);
execl("/bin/sort", "sort", 0);
}
Now this does exactly what it is supposed to do, last | sort , I'm trying to do all this with popen instead. Here is my attempt at that.
Code:
int main(void)
{
FILE *fr, *fw;
int i, j=0;
char buffer[BUFSIZE];
fr = popen("last", "r");
fw = popen("sort", "w");
while (fgets(buffer, sizeof(buffer), fr))
fprintf(fw, "%s\n", buffer);
pclose(fr);
pclose(fw);
return 0;
}
This almost works perfectly, except I get 10000 blank lines printing to stdout first. I know it's 10000 because I through in a counter at one point. After the blank lines it outputs semi-properly. every 10 lines or so a line that's not sorted properly appears. Thanks for any help/advice on this.