如何确定bash中哪些对伪tty端口相互连接

时间:2018-07-05 23:01:49

标签: bash shell pty socat

我有一对使用伪终端/dev/pts/*相互通信的linux C程序。可以通信的pty作为命令行参数传递给这些程序。

我可以使用socat创建一对pty设备,如下所示:

socat -d -d pty,raw,echo=0 pty,raw,echo=0

上面的输出为:

2018/07/05 17:56:54 socat[58319] N PTY is /dev/pts/1
2018/07/05 17:56:54 socat[58319] N PTY is /dev/pts/3
2018/07/05 17:56:54 socat[58319] N starting data transfer loop with FDs [7,7] and [9,9]

如何从/dev/pts/*的输出中提取pty节点socat并通过命令行在shell脚本中传递给我的应用程序:

$./test_pty_app /dev/pts/1 & 
$./test_pty_app /dev/pts/2 &

我看到了一个类似的问题,可以在python here中执行此操作 谢谢!

2 个答案:

答案 0 :(得分:1)

 arr=($(socat -d -d pty,raw,echo=0 pty,raw,echo=0 2>&1 | grep -oh "/dev/pts/\w*"))

现在"${arr[0]}""${arr[1]}"是您的两个tty端口。

grep -oh仅打印出它匹配的模式,没有其他内容。 `/ dev / pts / \ w *仅匹配以/ dev / pts /开头的内容,然后匹配任意数量的字母数字(或_)字符,这基本上表示“直到单词结尾”。

答案 1 :(得分:1)

更新后的答案

如果socat必须作为背景,看来您将不得不使用文件。

( socat ... 2>&1 | grep -Eo "/dev/pts/\d+" > /tmp/a ) &
portA=$(head -n 1 /tmp/a)
portB=$(tail -n 1 /tmp/a)

原始答案

@jeremysprofile的答案可能更明智,但仅出于娱乐目的,您还可以执行以下任一操作:

socat ... | grep -Eo "/dev/pts/\d+" | { read portA; read portB; }

或者,使用bash的“进程替换” ,您可以执行以下操作:

{ read portA; read portB; } < <(socat ... | grep -Eo "/dev/pts/\d+")

然后您将在其中任何一个之后执行此操作:

./test_pty_app $portA &
./test_pty_app $portB &