【问题标题】:How does `lseek` help determine whether a file is empty?`lseek` 如何帮助确定文件是否为空?
【发布时间】:2021-04-16 20:22:11
【问题描述】:

我正在查看来自 GNU coreutils 的 catsource code,尤其是圆形检测。他们正在比较设备和 inode 并且工作正常,但是有一个额外情况,如果输入为空,他们允许输出作为输入。查看代码,这必须是lseek (input_desc, 0, SEEK_CUR) < stat_buf.st_size) 部分。我阅读了从 git blame 找到的手册页和 discussion,但我仍然不太明白为什么需要调用 lseek

这是cat 检测的要点,如果它会无限耗尽磁盘(请注意,为简洁起见,还删除了一些错误检查,完整的源代码链接在上面):

struct stat stat_buf;
fstat(STDOUT_FILENO, &stat_buf);
out_dev = stat_buf.st_dev;
out_ino = stat_buf.st_ino;
out_isreg = S_ISREG (stat_buf.st_mode) != 0;

// ...
// for <infile> in inputs {
    input_desc = open (infile, file_open_mode); // or STDIN_FILENO
    fstat(input_desc, &stat_buf);
    /* Don't copy a nonempty regular file to itself, as that would
       merely exhaust the output device.  It's better to catch this
       error earlier rather than later.  */
    if (out_isreg 
        && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
        && lseek (input_desc, 0, SEEK_CUR) < stat_buf.st_size)         // <--- This is the important line
    {
      // ...
    }
// } (end of for)

我有两种可能的解释,但似乎都有点奇怪。

  1. 根据某些标准(posix),一个文件可能是“空的”,尽管它仍然包含一些信息(用st_size 计算)并且lseekopen 通过默认偏移来尊重这些信息。我不知道为什么会这样,因为空意味着空,对吧?
  2. 这种比较实际上是两个条件的“巧妙”组合。这首先对我来说是有意义的,因为如果input_desc 将是STDIN_FILENO 并且不会有文件通过管道传输到stdinlseek 将失败并出现ESPIPE(根据手册页)并返回@ 987654337@。那么,整个语句将是lseek(...) == -1 || stat_buf.st_size &gt; 0。但这不可能是真的,因为只有在设备和 inode 相同的情况下才会进行此检查,并且只有在 a) stdin 和 stdout 指向相同的 pty 时才会发生这种情况,但是 out_isreg 将是 false 或 b) stdin 和stdout 指向同一个文件,但是lseek 不能返回-1,对吧?

我还编写了一个小程序,打印出返回值和errno 的重要部分,但对我来说没有什么突出的:

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char **argv) {
  struct stat out_stat;
  struct stat in_stat;

  if (fstat(STDOUT_FILENO, &out_stat) < 0)
    exit(1);

  printf("this is written to stdout / into the file\n");

  int fd;
  if (argc > 1)
    fd = open(argv[1], O_RDONLY);
  else
    fd = STDIN_FILENO;

  fstat(fd, &in_stat);
  int res = lseek(fd, 0, SEEK_CUR);
  fprintf(stderr,
          "errno after lseek = %d, EBADF = %d, EINVAL = %d, EOVERFLOW = %d, "
          "ESPIPE = %d\n",
          errno, EBADF, EINVAL, EOVERFLOW, ESPIPE);

  fprintf(stderr, "input:\n\tlseek(...) = %d\n\tst_size = %ld\n", res,
          in_stat.st_size);

  printf("outsize is %ld", out_stat.st_size);
}

$ touch empty
$ ./a.out < empty > empty
errno after lseek = 0, EBADF = 9, EINVAL = 22, EOVERFLOW = 75, ESPIPE = 29
input:
        lseek(...) = 0
        st_size = 0
$ echo x > empty
$ ./a.out < empty > empty
errno after lseek = 0, EBADF = 9, EINVAL = 22, EOVERFLOW = 75, ESPIPE = 29
input:
        lseek(...) = 0
        st_size = 0

所以我的研究没有触及我的最终问题:lseek 如何帮助确定在此示例中来自cat 源代码的文件是否为空?

【问题讨论】:

    标签: c unix posix gnu lseek


    【解决方案1】:

    这是我对它进行逆向工程的尝试——我找不到任何公开讨论来解释为什么将lseek() 放在那里(GNU coreutils 中没有其他地方这样做)。

    指导性问题是:lseek (input_desc, 0, SEEK_CUR) &lt; stat_buf.st_size 条件何时为假?

    测试用例:

    #!/bin/bash
    # (edited based on comments)
    
    set -x
    
    # arrange for cat to start off past the end of a non-empty file
    
    echo abcdefghi > /tmp/so/catseek/input
    # get the shell to open the input file for reading & writing as file descriptor 7
    exec 7<>/tmp/so/catseek/input
    # read the whole file via that descriptor (but leave it open)
    dd <&7
    # ask linux what the current file position of file descriptor 7 is
    # should be everything dd read, namely 10 bytes, the size of the file
    grep ^pos: /proc/self/fdinfo/7
    # run cat, with pre and post content so that we know how to locate the interesting part
    # "-" will cause cat to reuse its file descriptor 0 rather than creating a new file descriptor
    # the redirections tell the shell to redirect file descriptors 1 and 0 to/from our open file descriptor 7
    # which, as you'll remember, already has a file position of 10 bytes
    strace -e lseek ./src/cat /tmp/so/catseek/pre - /tmp/so/catseek/post <&7 >&7
    # now let's see what's in the file
    cat /tmp/so/catseek/input
    

    与:

    $ cat /tmp/so/catseek/pre
    pre
    $ cat /tmp/so/catseek/post
    post
    

    catlseek (input_desc, 0, SEEK_CUR) &lt; stat_buf.st_size

    + test.sh:8:echo abcdefghi
    + test.sh:10:exec
    + test.sh:12:dd
    abcdefghi
    0+1 records in
    0+1 records out
    10 bytes copied, 2.0641e-05 s, 484 kB/s
    + test.sh:15:grep '^pos:' /proc/self/fdinfo/7
    pos:    10
    + test.sh:20:strace -e lseek ./src/cat /tmp/so/catseek/pre - /tmp/so/catseek/post
    lseek(0, 0, SEEK_CUR)                   = 14
    +++ exited with 0 +++
    + test.sh:22:cat /tmp/so/catseek/input
    abcdefghi
    pre
    post
    

    cat0 &lt; stat_buf.st_size

    + test.sh:8:echo abcdefghi
    + test.sh:10:exec
    + test.sh:12:dd
    abcdefghi
    0+1 records in
    0+1 records out
    10 bytes copied, 3.6415e-05 s, 275 kB/s
    + test.sh:15:grep '^pos:' /proc/self/fdinfo/7
    pos:    10
    + test.sh:20:strace -e lseek ./src/cat /tmp/so/catseek/pre - /tmp/so/catseek/post
    ./src/cat: -: input file is output file
    +++ exited with 1 +++
    + test.sh:22:cat /tmp/so/catseek/input
    abcdefghi
    pre
    post
    

    如您所见,当cat 开始时,文件位置可能已经在文件结尾之后,仅检查文件大小会使cat 跳过文件,但也会触发失败,如if 语句中的代码是:

    error (0, 0, _("%s: input file is output file"), infile);
    ok = false;
    goto contin;
    

    使用lseek() 允许cat 说“哦,文件是相同的,并且不是空的,但是我们的读取仍然会变为空,因为这就是读取过去 EOF 的方式,所以我们可以允许这种情况”。

    【讨论】:

    • 我想你明白了,恭喜!实际上,问题在于源代码和相关讨论中的措辞方式。这不是要跳过空文件,而是要跳过还有要读的文件。
    • 我找不到任何公开讨论来解释为什么将lseek() 放在那里(GNU coreutils 中没有其他地方这样做) 给你:austingroupbugs.net/view.php?id=876跨度>
    • @AndrewHenle 你能更具体一点吗? (也许在正确的评论中添加一个#c1234 锚)我在该讨论中没有看到任何与他们的答案中刚刚解释的根有关的任何内容。这个线程似乎只是关于跳过空文件而不是失败并显示错误消息,但跳过空文件并不需要 lseek()。
    • @root 在您的回答中值得一提的是,lseek() 条件仅解决参数为-(即fd = STDIN_FILENO)的情况,因为文件偏移量未被重置open()。 lseek 测试使echo foo &gt; out; (read; cat pre - post) &lt;&gt; out &gt;&amp;0 不会发出错误,但echo foo &gt; out; (read; cat pre out post) &lt;&gt; out &gt;&amp;0 正确地抱怨输入和输出是同一个文件。 echo foo &gt; out; (read; cat pre /dev/stdin post) &lt;&gt; out &gt;&amp;0也一样
    • @NiklasMohrin 在我的 sn-ps 中 &gt;&amp;0 是一个基本上调用 dup2(0, 1) 的 shell 语法,即将标准输出重定向到标准输入(out 文件在 R/W 模式下用 @ 打开987654350@)。同样,在答案中,exec 7&lt;&gt;file 使 fd #7 在 shell 会话的其余部分以 R/W 模式访问文件,dd &lt;&amp;7 中的 &lt;&amp;7dup2(7, 0),即重定向标准输入到文件.重要的是共享同一个打开的文件,以便偏移量(/proc/*/fdinfo/0 中的 SEEK_CUR = pos 行)也被共享。顺便说一句,我能找到的最小插图是&gt; out; cat pre - post &lt;&gt; out &gt;&amp;0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2013-06-14
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多