0

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;
}
3
  • You can't redirect the stdout of the shell command like that. Do echo "Hello" | ./my_program instead. Commented May 4, 2022 at 16:50
  • 1
    Or ./my_program < <(echo "Hello") -- note the extra < there not in the OP's command. Commented May 4, 2022 at 16:51
  • 3
    By doing ./my_program <(echo "Hello") you are not redirecting stdin, you are substituting the results of the command by a file descriptor. If you want to redirect that file descriptor to stdin, you have to add the redirection: ./my_program < <(echo "Hello") Commented May 4, 2022 at 16:52

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.