2015-09-25 147 views
1

我正在寻找使用bash脚本控制已编译的C程序X的执行流程。程序X仅产生文本输出,并且我希望在打印某个字符串时立即暂停执行。在此之后,我想切换到bash并执行一些命令,然后返回到完成X.我已经做了一些阅读和测试,只希望/ bash脚本似乎满足我的需求。但是,我在实现自己的目标方面遇到困难。Bash/expect脚本来控制执行

我已经试过了期待脚本中产卵X然后期望“MyString的”其次发送 bash脚本命令,但这只是导致X终止命令后,正在执行的是bash。

有没有人知道实现这个方法?为了澄清,我不能在这种情况下使用gdb。

#!/usr/bin/expect 
spawn X 
expect "mystring" 
send -- "bash command" 
+0

表明您已经写 – deimus

+0

我有加的最小脚本的最小脚本 – stantheman

+0

还有的将是当X输出之间不可避免的延迟字符串,当X实际上暂停时:检测字符串并对其作出反应所需的时间。我假设你的bash命令是用来修改X将如何继续的;你确定你可以暂停X来完成这个任务吗? – chepner

回答

1

我会生成一个shell而不是直接产生X.然后,您可以使用shell向程序发送一个SIGSTOP以暂停它(除非程序有能力在您直接发送内容时暂停)。

的演示

#!/usr/bin/expect -f 

spawn bash 
send "unset PROMPT_COMMAND; PS1=:\r" ;# I have a fairly tricky bash prompt 
expect -re ":$" 

# this stands-in for "X": start a shell that sends stuff to stdout 
send {sh -c 'n=1; while [ $n -lt 10 ]; do echo $n; sleep 1; let n=n+1; done'} 
send "\r" 

# when I see "5", send a Ctrl-Z to suspend the sh process 
expect 5 {send \x1a} 
expect -re ":$" 

# now do some stuff 
send "echo hello world\r" 
expect -re ":$" 
send "echo continuing\r" 
expect -re ":$" 

# and re-commence "X" 
send "fg\r" 
expect -re ":$" 

# and we're done 
send "exit\r" 
expect eof 

并运行它:

$ expect intr.exp 
spawn bash 
unset PROMPT_COMMAND; PS1=: 
$ unset PROMPT_COMMAND; PS1=: 
:sh -c 'n=1; while [ $n -lt 10 ]; do echo $n; sleep 1; let n=n+1; done' 
1 
2 
3 
4 
5 
^Z 
[1]+ Stopped     sh -c 'n=1; while [ $n -lt 10 ]; do echo $n; sleep 1; let n=n+1; done' 
:echo hello world 
hello world 
:echo continuing 
continuing 
:fg 
sh -c 'n=1; while [ $n -lt 10 ]; do echo $n; sleep 1; let n=n+1; done' 
6 
7 
8 
9 
:exit 
exit 
+0

它的工作!非常感谢。你是天赐之物! – stantheman