【问题标题】:Why extra characters ^@ appended when using mmap?为什么在使用 mmap 时附加了额外的字符 ^@?
【发布时间】:2013-10-22 13:42:15
【问题描述】:

我尝试了一个简单的mmap相关C sn-p:

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

int main(int argc, char** argv) {
  int fd;
  char* mapped_mem;
  int flength = 1024;
  void* start_addr = 0;

  if (argc < 2) {
    printf("usage: %s filename\n", argv[0]);
    exit(1);
  }

  fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  flength = lseek(fd, 1, SEEK_END);
  write(fd, "\0", 1);

  lseek(fd, 0, SEEK_SET);
  printf("fd=%d, flength=%d\n", fd, flength);
  mapped_mem = mmap(start_addr, flength, PROT_READ, MAP_PRIVATE, fd, 0);

  printf("%s\n", mapped_mem);
  close(fd);
  munmap(mapped_mem, flength);

  return 0;
}

但是我发现每次在数据文件上执行它时,^@^@ 都会附加到这个文件上。那到底是怎么回事?

【问题讨论】:

  • 由于 ^@ 是 Control-@ 的典型符号,因此是一个零字节,也许您的查看器只是以这种方式显示两个零字节?您可以使用xxd 进行检查以查看 hexdump。

标签: c linux memory-management posix mmap


【解决方案1】:

您的程序首先将 1 个字节移出文件末尾(lseek),然后在那里写入一个零字节(write)。实际上,两个零字节被附加到您的文件中,其中一个字节填补了文件末尾和写入位置之间的空白。

mmap 在这方面没有任何改变。损坏已经造成。

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多