mmap/mmapcp.cc

40 lines
1.3 KiB
C++
Raw Permalink Normal View History

2016-09-29 18:28:39 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>
#include <sys/stat.h>
2016-10-02 20:21:02 +00:00
int main (int argc, char *argv[]) {
struct stat st, s2t;
2016-10-03 15:21:20 +00:00
2016-10-03 01:20:44 +00:00
int s = open(argv[1], O_RDONLY);
2016-10-02 20:21:02 +00:00
if (s == -1) { perror("open source"); exit(1); }
2016-10-03 15:11:47 +00:00
2016-10-03 01:20:44 +00:00
int s2 = open(argv[2], O_RDONLY);
2016-10-02 20:21:02 +00:00
if (s2 == -1) { perror("open source2"); exit(1); }
2016-10-03 15:11:47 +00:00
2016-10-03 15:21:20 +00:00
int d = open(argv[3], O_RDWR | O_CREAT | O_EXCL, 0644);
2016-10-02 20:21:02 +00:00
if (d == -1) { perror("open destination"); exit(1); }
2016-10-03 15:11:47 +00:00
2016-10-02 20:21:02 +00:00
if (fstat(s, &st)) { perror("stat source"); exit(1); }
if (fstat(s2, &s2t)) { perror("stat source2"); exit(1); }
if (ftruncate(d, st.st_size + s2t.st_size)) { perror("truncate destination"); exit(1); }
2016-10-03 15:11:47 +00:00
2016-10-03 01:20:44 +00:00
void *sp = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, s, 0);
2016-10-02 20:21:02 +00:00
if (sp == MAP_FAILED) { perror("map source"); exit(1); }
madvise(sp, st.st_size, MADV_SEQUENTIAL);
2016-10-03 15:11:47 +00:00
2016-10-03 01:20:44 +00:00
void *s2p = mmap(NULL, s2t.st_size, PROT_READ, MAP_SHARED, s2, 0);
2016-10-02 20:21:02 +00:00
if (s2p == MAP_FAILED) { perror("map source2"); exit(1); }
madvise(s2p, s2t.st_size, MADV_SEQUENTIAL);
2016-10-03 15:11:47 +00:00
2016-10-03 01:20:44 +00:00
void *dp = mmap(NULL, st.st_size + s2t.st_size, PROT_WRITE | PROT_READ, MAP_SHARED, d, 0);
2016-10-02 20:21:02 +00:00
if (dp == MAP_FAILED) { perror("map destination"); exit(1); }
madvise(dp, st.st_size + s2t.st_size, MADV_SEQUENTIAL);
2016-10-03 15:11:47 +00:00
2016-10-02 20:21:02 +00:00
memcpy(mempcpy(dp, sp, st.st_size), s2p, s2t.st_size);
2016-10-02 19:35:02 +00:00
return 0;
2016-09-29 18:28:39 +00:00
}