2014-10-20 31 views
1

我有一个交互式C程序,我想使用.sh脚本进行测试。 我创建了一个基于这些方向:https://unix.stackexchange.com/questions/21759/how-to-send-input-to-a-c-program-using-a-shell-script,它工作正常,但屏幕上的输出是不好的。 我希望输入在屏幕上显示,并在输入后用新行显示,与用户手动输入所有内容时的显示方式相同。现在显示的方式是提示符,然后是空格,然后是下一个提示符,依此类推。使用.sh脚本测试C程序时显示输入

我看了很多不同的问题,但都没有提供答案。 我可以每次从程序本身打印输入,但这意味着即使用户手动输入数据,也会打印输入。

我明白,这是因为输入来自文件而不是命令行,但我仍然想解决这个问题。 无论如何我可以做到这一点吗?我不能使用任何外部工具,因为我必须为一个类提交此脚本。

+1

您是否考虑过使用['expect'](http://en.wikipedia.org/wiki/Expect)(或['pexpect'](https://github.com/pexpect/pexpect)) ? – John1024 2014-10-20 02:50:06

+0

我有,但正如我之前提到的,我不能使用任何工具,因为我非常怀疑分级的人会期望什么或者已经安装了哪些工具。 – user1356809 2014-10-20 03:21:53

+0

.sh将与我们在大学使用的所有Linux计算机一起使用,以便我可以安全地使用它。 – user1356809 2014-10-20 03:22:34

回答

1

如果你可以使用bash,并且 - 例如 - 你的程序输出的每一行输入一条线,那么所有你需要从你的shell脚本做的是:

  1. 存储您的输入。
  2. 将它传递给你的程序并存储输出。
  3. 交替地回显每条输入和输出线。

以下是一个C程序,这只是呼应输入给它的任何线,以“您输入”前缀:

#include <stdio.h> 

int main(void){ 
    char buffer[1024]; 

    while (fgets(buffer, 1024, stdin)) { 
     printf("You entered: %s", buffer); 
    } 

    return 0; 
} 

如果我们从终端运行,如果,我们得到这样的:

[email protected]:~/src/sandbox$ ./sample 
first line 
You entered: first line 
second line 
You entered: second line 
third line 
You entered: third line 
[email protected]:~/src/sandbox$ 

(使用CTRL-D在输入第三行后终止输入)。

这里有一个bash脚本来模拟:

#!/bin/bash 

# Pass input to program and store output 

input=$'first line\nsecond line\nthird line' 
output=`echo "$input" | ./sample` 

# Split input and output lines to arrays 

IFS=$'\n' 
inlines=($input) 
outlines=($output) 

# Alternately print input and outline lines 

for i in "${!inlines[@]}"; do 
    echo "${inlines[$i]}" 
    echo "${outlines[$i]}" 
done 

这给输出:

[email protected]:~/src/sandbox$ ./test_sample.sh 
first line 
You entered: first line 
second line 
You entered: second line 
third line 
You entered: third line 
[email protected]:~/src/sandbox$ 

它等同于它的外观在交互式会话。

如果你的程序没有使用像这样的简单的逐行呼叫和响应,那么你将有更多的工作要做,但如果你有所有的输入和输出线路,而你知道该期待什么,那么这是可行的,因为在程序结束后,您仍然可以访问所有输入和所有输出,并且可以根据需要回显它们。