使用mmap()的复制命令的变体中的问题

问题描述 投票:-1回答:1

我有一个程序,它是linux中复制程序的另一个变体(实际上,我在Mac OSX上)。为了支持复制大文件,我写了这样的内容:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mman.h>
#define BUFFSIZE 1024

int main(int argc, char **argv){
  char *source, *destination;
  int src_fd, dst_fd;
  unsigned long long bytes_read;
  size_t bytes;
  struct timeval start, end;
  int overall_time = 0;
  unsigned long long offset = 0;
  struct stat statbuf;
  if(argc < 3){
    printf("copy <source> <destination>\n");
    exit(EXIT_FAILURE);
  }
source = argv[1];
  destination = argv[2];

  src_fd = open(source, O_RDONLY, 0777);
  if(src_fd < 0){
    perror("src_fd");
    exit(EXIT_FAILURE);
  }
  //bytes_read = lseek(src_fd, 0, SEEK_END);
  fstat(src_fd, &statbuf);
  bytes_read = statbuf.st_size;
  dst_fd = open(destination, O_RDWR | O_CREAT, 0777);
  if(dst_fd < 0){
    perror("dst_fd");
    exit(EXIT_FAILURE);
  }
  lseek(dst_fd, bytes_read -1, SEEK_SET);
  write(dst_fd, "", 1);

  gettimeofday(&start, NULL);
  while(bytes_read > 0){
    if(bytes_read < BUFFSIZE){
      bytes = bytes_read;
      bytes_read = 0;
    }
    else{
      bytes = BUFFSIZE;
    }
    void *src_map = mmap(NULL, bytes, PROT_READ, MAP_SHARED, src_fd, (off_t)offset);
    if(src_map == (void*) MAP_FAILED){
      perror("src_map");
      exit(EXIT_FAILURE);
    }

    void *dst_map = mmap(NULL, bytes, PROT_WRITE, MAP_SHARED, dst_fd, (off_t)offset);
    if(dst_map == (void*) MAP_FAILED){
      perror("dst_map");
      exit(EXIT_FAILURE);
    }

    memcpy(dst_map, src_map, bytes);

    int src_unmp = munmap(src_map, bytes);
    if(src_unmp == -1){
      perror("src_unmap");
      exit(EXIT_FAILURE);
    }
    int dst_unmp = munmap(dst_map, bytes);
    if(dst_unmp == -1){
      perror("dst_unmap");
      exit(EXIT_FAILURE);
    }
    offset += bytes;
    bytes_read -= bytes;
  }
  gettimeofday(&end, NULL);
  printf("overall = %d\n", (end.tv_usec - start.tv_usec));
  close(src_fd);
  close(dst_fd);
  return 0;
}

在while语句中,程序尝试进​​行第一次迭代,并在尝试为mmap()调用src_fd时停留在第二次迭代中(第29行)。我希望程序可以正常运行,但在第二次迭代中会引发“ src_map:无效参数”错误。我个人认为是因为offset。有人可以帮我吗?谢谢

c shared-memory mmap
1个回答
0
投票

是。问题出在偏移值上。偏移值应为页面大小的倍数。

© www.soinside.com 2019 - 2024. All rights reserved.