Linux cat 命令源码剖析(2)

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 bool
simple_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"));
      }
    }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/23d7a2949351148d75623cc15a0e7403.html