ナンモワカランアザラシ

Ringed seal, clueless still

TTY・PTYってなんだ、`docker exec`コマンドの`-t`って何してるんだ

ターミナル関係でよく聞く言葉、という認識しかなかったので調べてまとめる。 dockerコマンドの-tオプションが何をやってるのかが分かるのをゴールとする。

TTYとは何か

信頼できない情報源の記述をまとめると、TTYとはどうやらUnixLinuxが持つ機能の一部らしい。

https://www.kernel.org/doc/html/latest/driver-api/tty/index.html

Linux Kernel Documentation』内に説明ページがあった。

Teletypewriter (TTY) layer takes care of all those serial devices. Including the virtual ones like pseudoterminal (PTY).

TTYとはTeletypewriterの略であり、疑似端末を含むシリアルデバイスの面倒を見るレイヤーだそうだ。

シリアルデバイスとは?

シリアルデバイスは、シリアルデータを送受信できるデバイスである。 シリアルデータとは、連続的なデータである。データを1ビットずつ連続して送受信できる装置がシリアルデバイスだ。

「面倒を見る」とは何をしているのか?

Every character received by the kernel (both from devices and users) is passed through a preselected TTY Line Discipline (in short ldisc; in C, struct tty_ldisc_ops). Its task is to transform characters as defined by a particular ldisc or by user too. The default one is n_tty, implementing echoes, signal handling, jobs control, special characters processing, and more. The transformed characters are passed further to user/device, depending on the source.

カーネルが受信した文字(たぶんシリアルデータのこと)はTTY Line Disciplineというものを通過する。通過する際に、その文字をいい感じに変換してくれるくん、という理解であっているだろうか。 TTY Line Disciplineは"ldisc"と略される。略称にTTYは登場しないんだ。デフォルトのldiscはn_ttyというものである。n_tty`はなんかいろいろやってくれるらしい。便利。

pseudoterminal、PTYとは?

https://docs.kernel.org/filesystems/devpts.html

Each mount of the devpts filesystem is now distinct such that ptys and their indices allocated in one mount are independent from ptys and their indices in all other mounts.

このあたりから察するに、PTYとは物理端末ではない仮想シリアルデバイスのことだろう。Linuxファイルシステムにマウントされるようだ。

docker execコマンドの-t

https://docs.docker.jp/engine/reference/commandline/exec.htmlhttps://docs.docker.com/reference/cli/docker/container/exec/

-t, --tty

Allocate a pseudo-TTY

ここまでの議論からまとめると、docker execコマンドの-tとは、シリアルデータを送受信するための疑似端末をコンテナに割り当てるためのオプションである、と言えるだろう。つまり-tオプションをつけるとターミナルでコンテナに入出力できるようになる。