2015-09-25 144 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