下面是有交互界面的一段测试c程序:
test.c
#include <stdio.h>
int main()
{
int sec;
FILE *fp = NULL;
do{
printf("++++++++++++++++++++++\n");
printf("1: one\n");
printf("2: two\n");
printf("3: three\n");
printf("0: exit\n");
printf("++++++++++++++++++++++\n");
printf("Select:");
scanf("%d", &sec);
switch(sec) {
case 1:
if((fp = fopen("a.txt", "w")) != NULL) {
printf("one\n");
}
break;
case 2:
if((fp = fopen("b.txt", "w")) != NULL) {
printf("two\n");
}
break;
case 3:
if((fp = fopen("c.txt", "w")) != NULL) {
printf("three\n");
}
break;
case 0:
printf("exit\n");
break;
}
}while(sec != 0);
return 0;
}
需求是在用java调用该程序时,自动执行1,2,0,而不用人工手动实现交互。那么,这里需要一段小的脚本。
脚本采用的是expect,脚本如下:
P10Cmd.sh:
#!/usr/local/bin/expect
set timeout 30
spawn ./test
expect "Select:"
send "1\n"
expect "Select"
send “2\n”
expect "Select"
send "0\n"
expect eof
那么在java调用时:
String cmd = "/home/cert/P10Cmd.sh";
Process p = null;
p = Runtime.getRuntime().exec(cmd);
这样就实现了自动完成交互的功能。