Try   HackMD

リダイレクションってなに? - シェルもどきをgoで自作する #5

おさらい

これまで

シェルもどき「oreshell」を自作している。
空白文字を含んでいるファイル名/パス名(例:「cp \ oge "h ge"」)を扱えるようなった。

現状のoreshellはリダイレクションでエラーになる

空白文字を含んでいるファイル名/パス名を扱えるようになったが、他にもまだまだエラーが発生する。

$ cat hoge.txt
hoge
$ cat hage.txt
hage
$ cat hoge.txt - < hage.txt > result.txt
hoge
cat: -: Bad file descriptor
cat: '<': No such file or directory
hage
cat: '>': No such file or directory
cat: result.txt: No such file or directory
cat: closing standard input: Bad file descriptor

リダイレクションに対応していないためエラーになる。
(catでわざわざ「-」を使っているのは標準入力の例を示すため。)

リダイレクションとは

wikipediaより

リダイレクションとは、様々なシェルを含むほとんどのコマンドラインインタプリタに共通の機能であり、標準ストリームをユーザで指定した位置に変更する機能のこと。

通常、(posixの)一般的なプロセスは標準入出力を持つ。
プロセス生成時に

  • 標準入力はキーボード
  • 標準出力は画面
  • 標準エラー出力は画面

に結び付けられている。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

この結びつきを、リダイレクションによってその入力元や出力先をファイルなどに切り替えることができる。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

リダイレクションの指定には「>」「<」などを使う。

リダイレクションの例

■ 例「cat hoge.txt - < hage.txt > result.txt」

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

なぜ現状のoreshellではエラーになるのか、どのように修正するのか

現状のoreshellでは「-」「< hage.txt」「> hoge.txt」のすべての文字列をプロセス生成時にcatコマンドの引数としてOSカーネルに渡している。
リダイレクションはシェルで実現する機能である。OSカーネルに「>」や「<」の文字列を渡してもOSカーネル(が生成したcatプロセス)はこれらの文字列を理解できない(その名前のファイルを探そうとする)ためエラーになる。

■現状

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

「< hage.txt」や「> hoge.txt」の文字列はOSカーネルに渡す前に切り取る必要がある。
また、プロセス生成時に標準入力元/標準出力先/標準エラー出力先を「hage.txt」「hoge.txt」に切り替える機能が必要がある。

■修正予定

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →