将数据写入shell脚本中可执行文件的stdin

b1payxdu  于 2023-05-18  发布在  Shell
关注(0)|答案(1)|浏览(311)

我正在做一个项目,试图构建一些基本的功能。我运行的是简单的c代码,它从stdin文件流中读取数据并打印出来。下面附上了代码的简短片段。在我的应用程序中,我想启动一个c代码,它通过stdin读取数据并对其执行一些操作,并且会有另一个进程运行,周期性地将数据发送到stdin。检查伪shell脚本以更好地理解。由于我是shell脚本的初学者,我不知道如何完成这个任务。所以,请帮助我,如果有人做过类似的事情或有线索如何做。

#!/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( ));
}
wqlqzqxt

wqlqzqxt1#

我能告诉你的最好的就是:

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

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

请参阅https://mywiki.wooledge.org/BashFAQ/001中“输入源选择”部分的底部,了解为什么我使用process substitution结构中的< <(...)重定向而不是管道。

相关问题