Linux cat 命令源碼剖析,linuxcat源碼剖析

來源:互聯網
上載者:User

Linux cat 命令源碼剖析,linuxcat源碼剖析

最近在讀APUE, 邊看還得邊做才有效果. 正好linux下很多命令的是開源的, 可以直接看源碼. GNU coreutils 是個不錯的選擇. 源碼包有我們最常用的 ls, cat等命令的源碼, 每個命令都比較短小精悍, 適合閱讀. 下面是我閱讀 cat 命令的一點筆記.

到這裡下載源碼. 在源碼根目錄下 ./configure; make 就可以直接編譯, 修改後make就可以編譯了. 命令源碼在 src/目錄中, lib/目錄下有一些用到的輔助函數和常量定義.


1. 命令列解析

基本上所有的Linux命令都是用getopt函數來解析命令列參數的, cat也不例外, cat使用的是getopt_long函數, 以便解析長參數, 用一些bool變數來儲存選項值. 沒什麼好說的.


2. 檢測輸入輸出檔案是否相同

例如 cat test.txt > test.txt 的情況, 輸入輸出檔案相同, 這是不合法的. 

cat 的輸入資料流由命令列給定, 預設是標準輸入(stdin), 輸出資料流是標準輸出(stdout). 所以用字串比較的方法是無法判斷輸入輸出是否是相同.  另外對於一些特殊的檔案, 如tty, 我們是允許其輸入輸出相同的, 如 cat /dev/tty > /dev/tty 是合法的. cat採取的方式是對與regular file, 檢測裝置編號和i-node是否相同. 忽略對非regular file的檢測. 這部分的代碼如下:

獲得檔案屬性.

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


提取檔案裝置編號和i-node. 對於非 regular 類型的檔案, 忽視檢測.

if (S_ISREG (stat_buf.st_mode))    {      out_dev = stat_buf.st_dev;      out_ino = stat_buf.st_ino;    }  else    {      check_redirection = false;    }

進行檢查. check_redirection為false就不檢查.

 if (fstat (input_desc, &stat_buf) < 0)<span style="white-space:pre"></span>// input_desc為輸入檔案描述符        {          error (0, errno, "%s", infile);          ok = false;          goto contin;        }

if (check_redirection          && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino          && (<strong>input_desc != STDIN_FILENO</strong>))<span style="white-space:pre"></span>/*  若輸入為標準輸入或其重新導向, 也不檢測, 所以命令 cat <test >test 也是合法的 */        {          error (0, 0, _("%s: input file is output file"), infile);          ok = false;          goto contin;        }

Tips: '-'  表示的是標準輸入, 如 cat - 命令實際是從標準輸入讀取位元組. 所以cat可以配合管道命令這樣用: echo abcd | cat file1 - file2. 只輸入 cat 命令預設就是從標準輸入讀取位元組.

3. 一次讀寫的位元組數目

cat是以read, write函數為基礎實現的, 一次讀寫的位元組數的多少也影響了程式的效能.

insize 和 outsize 變數分別表示一次讀和寫的位元組數目.

insize = io_blksize (stat_buf);
enum { IO_BUFSIZE = 128*1024 };static inline size_tio_blksize (struct stat sb){  return MAX (IO_BUFSIZE, ST_BLKSIZE (sb));<span style="white-space:pre"></span>/* ST_BLKSIZE( )宏的值視系統而定, 在lib/stat-size.h中定義 */}

outsize值的設定類似insize.


4. simple_cat

如 cat 命令不使用任何格式參數, 如 -v, -t. 那麼就調用simple_cat來完成操作, simple_cat的優點是速度快, 因為它在某些系統上有可能是以二進位方式讀寫檔案. 參考 man 3 freopen.

if (! (number || show_ends || squeeze_blank))    {      file_open_mode |= O_BINARY;<span style="white-space:pre"></span>/* 在linux下O_BINARY為0, 沒有任何效果, 但有些系統是表示二進位形式開啟檔案 */      if (O_BINARY && ! isatty (STDOUT_FILENO))<span style="white-space:pre"></span>/* 調用 freopen, 包含錯誤處理, 將輸出資料流的mode改為"wb" */        xfreopen (NULL, "wb", stdout);    }

無任何格式參數, 則調用simple_cat

 if (! (number || show_ends || show_nonprinting             || show_tabs || squeeze_blank))        {          insize = MAX (insize, outsize);<span style="white-space:pre"></span> /* xzz 分配記憶體, 失敗則調用 xmalloc-die() 終止程式並報告錯誤 */          inbuf = xmalloc (insize + page_size - 1);          ok &= simple_cat (<strong>ptr_align</strong> (inbuf, page_size), insize);        }

ptr_align是一個輔助函數. 因為IO操作一次讀取一頁, ptr_align是使得緩衝數組的起始地址為也大小的整數倍, 以增加IO的效率.

static inline void *ptr_align (void const *ptr, size_t alignment){  char const *p0 = ptr;  char const *p1 = p0 + alignment - 1;  return (void *) (p1 - (size_t) p1 % alignment);}


simple_cat函數很簡單

static boolsimple_cat (     /* Pointer to the buffer, used by reads and writes.  */     char *buf,     /* Number of characters preferably read or written by each read and write        call.  */     size_t bufsize){  /* Actual number of characters read, and therefore written.  */  size_t n_read;  /* Loop until the end of the file.  */  while (true)    {      /* Read a block of input.  *//*  普通的read可能被訊號中斷*/      n_read = safe_read (input_desc, buf, bufsize);      if (n_read == SAFE_READ_ERROR)        {          error (0, errno, "%s", infile);          return false;        }      /* End of this file?  */      if (n_read == 0)        return true;      /* Write this block out.  */      {        /* The following is ok, since we know that 0 < n_read.  */        size_t n = n_read;/* full_write 和 safe_read都調用的是 safe_sw, 用宏實現的, * 查看 safe_write.c 就可以發現其實現的關鍵. */        if (full_write (STDOUT_FILENO, buf, n) != n)          error (EXIT_FAILURE, errno, _("write error"));      }    }}


5. safe_rw, full_rw 函數

read 和write函數在讀寫第一個字元之前有可能被signal中斷, safe_rw可以恢複被中斷的read和write過程. 這個函數非常tricky, 它的名字safe_rw和rw其實都是宏定義, 條件編譯可以將此函數編譯成safe_read, safe_write兩個函數.

<strong>size_t </strong>/* 原始的read()函數傳回值是 ssize_t */safe_rw (int fd, void const *buf, size_t count){  /* Work around a bug in Tru64 5.1.  Attempting to read more than     INT_MAX bytes fails with errno == EINVAL.  See     <http://lists.gnu.org/archive/html/bug-gnu-utils/2002-04/msg00010.html>.     When decreasing COUNT, keep it block-aligned.  */  enum { BUGGY_READ_MAXIMUM = INT_MAX & ~8191 };  for (;;)    {      ssize_t result = rw (fd, buf, count);      if (0 <= result)        return result;  <strong>    else if (IS_EINTR (errno))<span style="white-space:pre"></span>/* signal 中斷 */        continue;</strong>      else if (errno == EINVAL && BUGGY_READ_MAXIMUM < count)        count = BUGGY_READ_MAXIMUM;      else<span style="white-space:pre"></span>/* 返回 (size_t) -1 */        return result;    }}


read, write 讀寫過程中有可能被 signal 中斷, full_rw 可以恢複讀寫過程, 直到讀寫到了指定數目的位元組或到達檔案結尾(EOF), 或者是讀寫出錯. 返回當前已經讀寫了的位元組數目. full_rw() 函數名也是宏定義的, 實際上實現了full_read() full_write().

/* Write(read) COUNT bytes at BUF to(from) descriptor FD, retrying if   interrupted or if a partial write(read) occurs.  Return the number   of bytes transferred.   When writing, set errno if fewer than COUNT bytes are written.   When reading, if fewer than COUNT bytes are read, you must examine   errno to distinguish failure from EOF (errno == 0).  */size_tfull_rw (int fd, const void *buf, size_t count){  size_t total = 0;  const char *ptr = (const char *) buf;  while (count > 0)    {      size_t n_rw = safe_rw (fd, ptr, count);      if (n_rw == (size_t) -1)<span style="white-space:pre"></span>/* error */        break;      if (n_rw == 0)<span style="white-space:pre"></span>/* reach EOF */        {          errno = ZERO_BYTE_TRANSFER_ERRNO;          break;        }      total += n_rw;      ptr += n_rw;      count -= n_rw;    }  return total;}

Tips : 查看lib目錄下safe_read.c 和 safe_write.c檔案可以看到這個函數怎樣被展開成兩個不同的函數的.


6. cat 函數, 處理格式化輸出

simple_cat只是將輸入原封不動的輸出, 沒有作任何處理, 所有與格式化輸出有關的內容都放在了 cat 函數裡面.

cat 函數的實現包含很多技巧. 例如使用一個哨兵'\n'來標記輸入緩衝區的結尾. 另外使用了一個字元數組來統計行數, 使得不支援64位整型的系統也可以使用很大範圍的數.

下面是這個行計數器的代碼.

/* Position in 'line_buf' where printing starts.  This will not change   unless the number of lines is larger than 999999.  */static char *line_num_print = line_buf + LINE_COUNTER_BUF_LEN - 8;/* Position of the first digit in 'line_buf'.  */static char *line_num_start = line_buf + LINE_COUNTER_BUF_LEN - 3;/* Position of the last digit in 'line_buf'.  */static char *line_num_end = line_buf + LINE_COUNTER_BUF_LEN - 3;

static voidnext_line_num (void){  char *endp = line_num_end;  do    {      if ((*endp)++ < '9')        return;      *endp-- = '0';    }  while (endp >= line_num_start);  if (line_num_start > line_buf)    *--line_num_start = '1';  else    *line_buf = '>';  if (line_num_start < line_num_print)    line_num_print--;}

理解這個函數的關鍵是搞懂newlines這個變數作用, cat格式化輸出主要的操作判斷換行和連續空行, newlines這個變數標記的是空行的數目, 值為0表示此時的inbuf的讀取位置在一行的開頭, 1表示有一個空行, -1 表示剛剛解析完一行, 準備進入下一行, 可以看到cat 函數最後的那個 while(true) 的兩個break語句都將 newlines 置為 -1.

cat格式化輸出的過程實際上就是逐一掃描輸入緩衝數組的過程, 並在掃描的過程中將轉化後的字元存入輸出緩衝數組中.



[助]對於linux源碼分析的一個問題:終端命令是怎別編譯的

這些命令其實都是一些程式,ls、tc這些跟編譯普通程式是一樣的過程;

這些命令的源檔案不在核心中,是在做檔案系統的時候定製的;

比如你想添加一個cat命令,那麼你只需要找到cat的源碼,編譯完後,放入你製作的檔案系統的/usr/bin目錄下面,那麼在啟動後就可以使用cat了;
 
誰可以給我一個Linux系統中du命令的詳細分析?(包括原始碼的分析)

Linux du命令也是查看使用空間的,但是與df命令不同的是Linux du命令是對檔案和目錄磁碟使用的空間的查看,還是和df命令有一些區別的,這裡介紹Linux du命令。
  du:查詢檔案或目錄的磁碟使用空間
  a:顯示全部目錄和其次目錄下的每個檔案所佔的磁碟空間
  b:大小用bytes來表示 (預設值為k bytes)
  c:最後再加上總計 (預設值)
  s:只顯示各檔案大小的總合
  x:只計算同屬同一個檔案系統的檔案
  L:計算所有的檔案大小
  常用命令:du –a
  操作詳解
  引用
  指令 du 能以指定的目錄下的子目錄為單位,顯示每個目錄內所有檔案所佔用的磁碟空間大小。例如:
  # du -h /etc
  104K /etc/defaults
  6.0K /etc/X11
  8.0K /etc/bluetooth
  4.0K /etc/gnats
  52K /etc/isdn
  388K /etc/mail
  68K /etc/mtree
  2.0K /etc/ntp
  38K /etc/pam.d
  44K /etc/periodic/daily
  6.0K /etc/periodic/monthly
  42K /etc/periodic/security
  16K /etc/periodic/weekly
  110K /etc/periodic
  6.0K /etc/ppp
  318K /etc/rc.d
  2.0K /etc/skel
  130K /etc/ssh
  10K /etc/ssl
  1.7M /etc
  我們目樣使用 -h 參數來顯示 human-readable 的格式。在應用時,我們可以使用 du 這個指令來查看哪個目錄佔用最多的空間。不過,du 的輸出結果通常很長,我們可以加上 -s 參數來省略指定目錄下的子目錄,而只顯示該目錄的總合即可:
  # du -sh /etc
  1.7M /etc
  在查看目錄的使用情形時,我們可以將輸出結果導到 sort 指令進行排序,以瞭解哪個檔案用了最多的空間:
  # du /etc | sort -nr | more
  1746 /etc
  388 /etc/mail
  318 /etc/rc.d
  130 /etc/ssh
  110 /etc/periodic
  104 /etc/defaults
  68 /etc/mtree
  52 /etc/isdn
  44 /etc/periodic/daily
  42 /etc/periodic/security
  38 /etc/pam.d
  16 /etc/periodic/weekly
  10 /etc/ssl
  8 /etc......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.