Home > OS >  C program is not reading redirected shell command standard input
C program is not reading redirected shell command standard input

Time:05-05

I have compiled the below c code which should send any input it receives in standard input to standard output. It works as expected in the following scenarios:

[user@host ~]$ ./my_program
test...
test...
^C
[user@host ~]$ echo "Hello" | ./my_program
Hello
[user@host ~]$ ./my_program < test.txt
Contents of test.txt ...

However, if I redirect the output of a shell command into my program like so:

[user@host ~]$ ./my_program <(echo "Hello")

It does not output anything and waits for input as if I started the program with just ./my_program

I expected an output of Hello and then the program to end. When I run the command cat <(echo "Hello") I get this expected result. What is causing the difference in behaviour between cat and my_program?

/* my_program.c */

#include <stdio.h>

int main()
{
    int c = getchar();
    while (c != EOF) {
        putchar(c);
        c = getchar();
    }
    return 0;
}

CodePudding user response:

Posting Community Wiki because the question is caused by a typo and thus off-topic.


You're passing a filename associated with a pipeline with the output of echo "Hello" on your program's command line, not attaching it to stdin.

To attach it to stdin you need an extra < on the command line:

./my_program < <(echo "Hello")

It works with cat the other way because when cat is passed command-line arguments, it treats them as files to read from.

  • Related