Bash/expect 控制执行的脚本
Bash/expect script to control execution
我希望使用 bash 脚本来控制已编译的 C 程序 X 的执行流程。程序 X 只产生文本输出,我想在打印某个字符串时立即暂停执行。在此之后,我想切换到 bash 并执行一些命令,然后 return 返回完成 X。我做了一些阅读和测试,只有 expect/bash 脚本似乎满足我的需要。但是,我很难实现我的目标。
我已经尝试在 expect 脚本中 spawning X 然后 expect "mystring" 然后 sending bash 脚本命令但这只会导致在 X 终止后执行 bash 命令。
有谁知道实现这个的方法吗?澄清一下,我不能在这种情况下使用 gdb。
#!/usr/bin/expect
spawn X
expect "mystring"
send -- "bash command"
我会生成 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
我希望使用 bash 脚本来控制已编译的 C 程序 X 的执行流程。程序 X 只产生文本输出,我想在打印某个字符串时立即暂停执行。在此之后,我想切换到 bash 并执行一些命令,然后 return 返回完成 X。我做了一些阅读和测试,只有 expect/bash 脚本似乎满足我的需要。但是,我很难实现我的目标。
我已经尝试在 expect 脚本中 spawning X 然后 expect "mystring" 然后 sending bash 脚本命令但这只会导致在 X 终止后执行 bash 命令。
有谁知道实现这个的方法吗?澄清一下,我不能在这种情况下使用 gdb。
#!/usr/bin/expect
spawn X
expect "mystring"
send -- "bash command"
我会生成 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