LoginSignup
0
0

os.pipe()が返すファイル記述子について

Last updated at Posted at 2024-02-01

疑問

パイプを使ってプロセス間でメッセージをやり取りするプログラムを作成していました。

その中で、os.pipe()の返すファイル記述子が毎回34になっているのはなぜか疑問に思いました。

import os

r, w = os.pipe()
print(r)
print(w)

# 3
# 4

回答

プロセスが開始されると、標準入力(stdin)、標準出力(stdout)、標準エラー出力(stderr)が自動的にファイル記述子0、1、2に割り当てられるためでした。

これにより、最初にプログラムが開くファイルやパイプのファイル記述子は、上記の標準ストリームの次の番号、つまり3から始まります。

import os
import sys

r, w = os.pipe()
pid = os.fork()

# 親プロセス
if pid > 0:
    print("stdinのファイル記述子:", sys.stdin.fileno())
    print("stdoutのファイル記述子:", sys.stdout.fileno())
    print("stderrのファイル記述子:", sys.stderr.fileno())
    print("読み取り端のファイル記述子:", r)
    print("書き込み端のファイル記述子:", w)
    os.close(r)
    message = "Message from parent with pid {}".format(os.getpid())
    print("Parent, sending out the message - {}".format(message))
    os.write(w, message.encode("utf_8"))
# 子プロセス
else:
    os.close(w)
    print("Fork is 0, this is a Child PID:", os.getpid())
    f = os.fdopen(r)
    print("Incoming string:", f.read())

# stdinのファイル記述子: 0
# stdoutのファイル記述子: 1
# stderrのファイル記述子: 2
# 読み取り端のファイル記述子: 3
# 書き込み端のファイル記述子: 4
# Parent, sending out the message - Message from parent with pid 88290
# Fork is 0, this is a Child PID: 88291
# Incoming string: Message from parent with pid 88290
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0