与来自不同进程的正在运行的交互式控制台程序进行交互

use*_*289 5 shell scripting bash background-process

我有一个带有交互式 shell 的控制台程序,类似于 Python 交互式 shell。有没有一种简单的方法可以启动这个交互式程序A,然后使用另一个程序B来运行A?我想做这样的事情:

$ /usr/bin/A&
$ #find PID of A somehow
$ somecommand "PID of A" "input string to send to A"
output string from A
$
Run Code Online (Sandbox Code Playgroud)

什么样的“somecommand”可以做到这一点?这是“期望”应该促进的吗?我阅读了expect手册页,但仍然不知道它的作用。

Joh*_*024 7

expect是为了不同的目的。它在俘虏程序上运行命令。相比之下,您正在寻求一种向已经在后台运行的进程发送命令的方法。

作为裸机的你想要的小例子,让我们创建一个FIFO:

$ mkfifo in
Run Code Online (Sandbox Code Playgroud)

FIFO 是一种特殊文件,一个进程可以写入该文件,而另一个进程可以从中读取。让我们创建一个进程来读取我们的 FIFO 文件in

$ python <in &
[1] 3264
Run Code Online (Sandbox Code Playgroud)

现在,让我们发送python一个命令从当前 shell 运行:

$ echo "print 1+2" >in
$ 3
Run Code Online (Sandbox Code Playgroud)

来自pythonis的输出3出现在 stdout 上。如果我们重定向了 python 的标准输出,它可以被发送到其他地方。

有什么expect作用

expect允许您自动与俘虏命令交互。作为expect可以做什么的示例,创建一个文件:

#!/usr/bin/expect --
spawn python
expect ">>>"
send "print 1+2\r"
expect ">>>"
Run Code Online (Sandbox Code Playgroud)

然后,使用以下命令运行此文件expect

$ expect myfile
spawn python
Python 2.7.3 (default, Mar 13 2014, 11:03:55) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 1+2
3
>>> 
Run Code Online (Sandbox Code Playgroud)