Given the following code, why does cat only print the contents of the pipe after I've typed \n
or CTRL+D? What are the conditions for cat to actually print what it read?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void){
int pid,p[2];
char ch;
pipe(p);
if((pid=fork()) == -1){
fprintf(stderr,"Error:can't create a child!\n");
exit(2);
}
if(pid){
close(p[0]);
while((ch=getchar())!=EOF){
write(p[1],&ch,1);
}
close(p[1]);
wait(0);
}else{
close(p[1]);
close(0);
dup(p[0]);
close(p[0]);
execlp("cat","cat",NULL);
}
return 0;
}
cat
on its own on the command line, you'll see it doesn't print anything until you press Return or Ctrl+D. That's the expected behavior. – ThibautRenaux May 07 '15 at 22:13http://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe
– Raymond Bannan May 07 '15 at 22:21while ((ch=getchar()) != EOF) { write(1,&ch,1); }
doesn't print anything until you press Return or Ctrl+D, either. – G-Man Says 'Reinstate Monica' May 08 '15 at 03:52