LoginSignup
8
6

More than 5 years have passed since last update.

[シェルコマンド]Catのメモリ使用量

Posted at

この記事

catコマンドのファイル読込がバッファ読込かどうか調査した。

結論

catはファイルシステムのブロックサイズに基づいて、Buffer読み込みをしてくれる。

調査

  1. catのソースを読む
  2. 実際の処理のメモリ使用量を確認

catのソースを読む

// ブロックサイズの取得
if (fstat (input_desc, &stat_buf) < 0){
    error (0, errno, "%s", infile);
    ok = false;
    goto contin;
}
insize = ST_BLKSIZE (stat_buf);

~(略)~

if (fstat (STDOUT_FILENO, &stat_buf) < 0)
    error (EXIT_FAILURE, errno, _("standard output"));
outsize = ST_BLKSIZE (stat_buf);

~(略)~

// insizeをバッファサイズに指定
insize = max (insize, outsize);
inbuf = xmalloc (insize + page_size - 1);
ok &= simple_cat (ptr_align (inbuf, page_size), insize);

~(略)~

// バッファ読込
n_read = safe_read (input_desc, buf, bufsize);

上記のように、ファイルシステムのBLOCK_SIZEを取得して、Bufferの大きさを設定している。

ブロックサイズの確認コード

blksizeChk.c
#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char **argv) {
  struct stat stat_buf;
  stat( *(argv + 1), &stat_buf);
  printf("ファイルシステムのブロックサイズ : %d\n", stat_buf.st_blksize);
  return 0;
}

上記のコードを下記のように実行する。

$ gcc blksizeChk.c
$ ./a.out hoge.dat
ファイルシステムのブロックサイズ : 4096

実際の処理のメモリ使用量を確認

適当に大きなサイズのファイルを作成して、catで開いた。

topで確認すると、
コンソールに標準出力する場合:500kb
パイプで他コマンドにつなげた場合:384kb
メモリ使用量だった。

参照

C言語入門講座
ボクノス GNU catを読む - 全体的な流れ
catコマンドのソース

8
6
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
8
6