Reputation: 792
Here is a short C program:
#include<stdio.h>
int main (void){
char cmd;
while(scanf("%c", &cmd) != EOF){
if(cmd == 'q'){
printf("Thanks\n");
return 0;
}
}
return 0;
}
When the following program is executed and value of cmd
is typed using keyboard, everything works as expected.
$ ./catproblem
q
Thanks
$
However, when I am trying to pipe the input using cat
, the program doesn't terminate right away when q
is entered. For some reason it waits for any other input and only then terminates.
$ cat | ./catproblem
q
Thanks
anything
$
What causes this behavior? And can this be fixed, so that the program works as expected if cat
is used for input?
Upvotes: 1
Views: 53
Reputation: 753545
The problem is that cat
has not terminated, and your shell (bash
) waits for all processes in the pipeline to terminate before continuing. When you type the line with anything
, cat
attempts to write to the pipe, gets a SIGPIPE signal, and terminates.
Upvotes: 4