Write data to stdin of an executable file in the shell script

I’m working on a project where I’m trying to build some basic functionality. I’m running simple c code, which reads the data from the stdin file stream and prints. The short snippet of the code is attached below. In my application, I want to start a c code which reads the data through stdin and performs some operation on it, and there will be another process running which sends the data to stdin periodically. Check the pseudo shell script for a better understanding. As I’m a beginner with shell scripting, I don’t know how to achieve this task. So, please help me if anyone has done something similar or has clues on how to do it.

#!/bin/sh
#I know this won't work because running code and cat command are referring to a different file stream
clear # clearing the screen
echo "running the shell command" #basic eco in the beginning
./a.out & # Run the compiled c code in the background 
while true 
  do
    sleep 2 #2-sec delay
    cat <<< "# check $\n" # send the data to the stdin
  done
exit 0

.

//regular c file, command: cc filename.c 
#include <stdio.h>
#include <unistd.h>
int FnReceiveCharacter(void)
{      
   unsigned char c = 0, d;
   d = read(STDIN_FILENO, &c, 1);
   fflush(stdin);   
   return c;
}
int main( )
{
  while(1) printf("%c",FnReceiveCharacter( ));
}

>Solution :

Best I can tell all you need is:

a.out < <(
    while true; do
        sleep 2
        echo '# check'
    done
)

For example, using a shell function calling awk instead of your C code which I can’t compile:

$ cat tst.sh
#!/usr/bin/env bash

foo() {
    awk '{ print "Received line", $0 }' "${@:--}"
}

foo < <(
    while true; do
        sleep 2
        echo '# check'
    done
)

$ ./tst.sh
Received line # check
Received line # check
...

See the bottom of the "Input source selection" section in https://mywiki.wooledge.org/BashFAQ/001 for why I’m using that < <(...) redirection from process substitution construct instead of a pipe.

Now that you updated your code to be compilable I did test it:

$ cat tst.sh
#!/usr/bin/env bash

./a.out < <(
    while true; do
        sleep 2
        echo '# check'
    done
)

$ ./tst.sh
# check
# check
# check

Leave a Reply