bash の双方向パイプ?

bash の双方向パイプ?

stdout が python スクリプトの stdin にリダイレクトされているバイナリがあり、python スクリプトの stdout をバイナリの stdin に送信して、次のような効果を得る方法があるかどうか疑問に思っています (ひどい ASCII 図で申し訳ありません)。


 |->-binary -- python -->-|
/|\                      \|/
 |-<---<---<---<---<---<--|

私の現在の bash コードは ですbinary | python3 pythonscript.py

ありがとう!

答え1

名前付きパイプを使用すれば、目的を達成できるはずです。各プロセスからの入力と出力の両方を他のプロセスにリダイレクトします。

binary < npipe1 > npipe2
python3 pythonscript.py < npipe2 > npipe1

名前付きパイプは次のようにすでに設定されているはずです。

mkfifo /dev/shm/npipe1
mkfifo /dev/shm/npipe2

名前付きパイプが共有メモリ ディレクトリに配置される場所ですが、その場所は必須ではありません。

以下は、bash および dash スクリプトを使用した簡単な例です。

doug@s19:~/temp$ cat test-fifo-job-control
#! /bin/dash
#
# test-fifo-job-control Smythies 2023.09.03
#       A simple example of using named pipes.
#       See https://askubuntu.com/questions/1484568/two-way-pipe-in-bash
#

# If they do not already exist, then create the named pipes.
# Note: sometimes they might need to be deleted and recreated.
#       i.e. if garbage was left in one, or both.

if [ ! -p /dev/shm/npipe1 ]
then
   mkfifo /dev/shm/npipe1
fi
if [ ! -p /dev/shm/npipe2 ]
then
   mkfifo /dev/shm/npipe2
fi

# Launch the first task
./test-fifo-part-1 < /dev/shm/npipe1 > /dev/shm/npipe2 &
#
# and supply the first input
echo 1000 >> /dev/shm/npipe1
#
# Now launch the second task
#./test-fifo-part-2 < /dev/shm/npipe2 > /dev/shm/npipe1
./test-fifo-part-2 < /dev/shm/npipe2 | tee /dev/shm/npipe1

#
# It'll go until stopped via ^C.

そして:

doug@s19:~/temp$ cat test-fifo-part-1
#!/bin/bash

while :
  do
# Note: No error checking
  read next_number
  echo "$next_number"
# Slow things down.
  sleep 1
done

そして:

doug@s19:~/temp$ cat test-fifo-part-2
#!/bin/bash

while :
  do
# Note: No error checking
  read next_number
  next_number=$((next_number+1))
  echo "$next_number"
# Slow things down.
  sleep 1
done

セッションの例:

doug@s19:~/temp$ ./test-fifo-job-control
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
^C
doug@s19:~/temp$

コメント内の追加の質問については:

Python コードではなく、bash スクリプトを使用してパイプしている場合でも、パイプに行かずに stdout に印刷する方法はありますか?

私が示した簡単な例ではそうではありません。通常、私はこれを C プログラムで使用し、出力を名前付きパイプに直接書き込むため、stdout は他の出力に使用できることに注意してください。

関連情報