python / python/cpython

os.forkpty() and pty.fork() return FD with O_CLOEXEC

オープン
#139,184 コメント 6 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

3.15 stdlib type-bug
主要言語
Python
スター
77.2k
フォーク
36k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:
(pid, fd) = pty.fork() # os.forkpty()
print('os.get_inheritable(fd))

https://docs.python.org/3/library/os.html#os.forkpty
https://docs.python.org/3/library/pty.html#pty.fork

Say nothing about that.

Lib/pty.py:

def fork():
    """fork() -> (pid, master_fd)
    Fork and make the child a session leader with a controlling terminal."""

    try:
        pid, fd = os.forkpty()
    except (AttributeError, OSError):
        pass
    else:
        if pid == CHILD:
            try:
                os.setsid()
            except OSError:
                # os.forkpty() already set us session leader
                pass
        return pid, fd

    master_fd, slave_fd = openpty()
    pid = os.fork()
    if pid == CHILD:
        os.close(master_fd)
        os.login_tty(slave_fd)
    else:
        os.close(slave_fd)

    # Parent and child process.
    return pid, master_fd

Also uses openpty() which also does not set O_CLOEXEC

Meanwhile, there is a C function posix_openpt(int flags); which allows setting O_CLOEXEC.

Seems, fd-leak safe solution is to boilerplate all the actions by hand. i.e. same way as pty.fork() does, but also implement openpty() using posix_openpt() + ptsname() / ptsname_r().

Just setting O_CLOEXEC after openpty() or after calling C forkpty() is not enough because of race-condition and possible file descriptor leak.

So, CLOEXEC behavior should be documented and race-condition prevented

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-139408

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Lib/pty.py と、文書化されているエントリポイント os.forkpty() および pty.fork() から開始し、続いてそれらの openpty() パスを、報告で言及されている posix_openpt(int flags) インターフェースと比較します。CLOEXEC の動作が文書化され、fork/openpty パスによって説明されている競合状態によるファイルディスクリプタのリークが防止されれば、作業は完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
operating-systems
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。