linux - Linux 中的文件漏洞是如何工作的

标签 linux io operating-system filesystems

我对文件漏洞在 Linux 上的工作方式有点困惑:

  int fd = open("/tmp/file1", O_RDWR | O_TRUNC);
  write(fd, "bbbb", 4);
  lseek(fd, SEEK_SET, 10000);
  write(fd, "aaaa", 4);
  lseek(fd, SEEK_SET, 50);
  write(fd, "cccc", 4);
  close(fd);

为什么 cat/tmp/file1 产生

bbbbaaaacccc

?不应该是bbbcccaaa吗?因为 aaaa 是在偏移量 10000 处写入的?

更新:lseek 使用 EINVAL 返回 -1。

最佳答案

因为“你确定 lseek 在所有调用中都成功了吗?你没有检查它的结果代码。”有助于确定我建议在您的文件系统调用之后添加的问题:

  int res = lseek(fd, 10000, SEEK_SET);
  if (res == -1) {
    perror("lseek has failed");
    return 1;
  }

你的问题是你以错误的顺序使用了参数:

lseek(fd, SEEK_SET, 10000); /* WRONG order for second and third parametes ! */

正确顺序:

lseek(fd, 10000, SEEK_SET);

这是一个人 lseek:

off_t lseek(int fd, off_t offset, int whence);

The lseek() function repositions the file offset of the open file
description associated with the file descriptor fd to the argument
offset according to the directive whence as follows:

SEEK_SET
      The file offset is set to offset bytes.

SEEK_CUR
      The file offset is set to its current location plus offset bytes.

SEEK_END
      The file offset is set to the size of the file plus offset
              bytes.

关于linux - Linux 中的文件漏洞是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37119123/

相关文章:

Linux 内核 : schedule() function in multi-processors system

linux - 如何同时将 bash 输出通过管道传输到文件和终端?

linux - "mvn -version"不返回版本

.net - File.Exists是一项昂贵的操作吗?

c - 在 fread(3) 中检查读取的项目数是否小于请求的数量,而不是 0,是否正确?

linux - 进程间实内存页读取?

linux - 使用 pgrep 获取 Linux 进程 ID

Linux Shell 脚本查找文件并重命名

python - 在偏移处读入字节数组?

c - 当我运行它时,此代码不执行任何操作。为什么?