.
This commit is contained in:
44
Fichiers/ex2/copy_mmap.c
Normal file
44
Fichiers/ex2/copy_mmap.c
Normal file
@@ -0,0 +1,44 @@
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
assert(argc == 3);
|
||||
|
||||
int fd_in = open(argv[1], O_RDONLY);
|
||||
assert(fd_in >= 0);
|
||||
|
||||
struct stat st;
|
||||
fstat(fd_in, &st);
|
||||
|
||||
// on mappe le fichier source en mémoire
|
||||
void *src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd_in, 0);
|
||||
assert(src != MAP_FAILED);
|
||||
|
||||
int fd_out = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0644);
|
||||
assert(fd_out >= 0);
|
||||
|
||||
// on fixe la taille du fichier de sortie
|
||||
ftruncate(fd_out, st.st_size);
|
||||
|
||||
// on mappe le fichier destination en mémoire
|
||||
void *dst = mmap(NULL, st.st_size, PROT_WRITE, MAP_SHARED, fd_out, 0);
|
||||
assert(dst != MAP_FAILED);
|
||||
|
||||
// copie mémoire → mémoire
|
||||
memcpy(dst, src, st.st_size);
|
||||
|
||||
// nettoyage
|
||||
munmap(src, st.st_size);
|
||||
munmap(dst, st.st_size);
|
||||
close(fd_in);
|
||||
close(fd_out);
|
||||
|
||||
return 0;
|
||||
}
|
Reference in New Issue
Block a user