From: Tomas Mudrunka Date: Tue, 21 Jul 2020 06:47:03 +0000 (+0200) Subject: better mmap example X-Git-Url: http://git.harvie.cz/?p=mirrors%2FPrograms.git;a=commitdiff_plain;h=b4d0545c57daf9761f3466c503153480d730180d better mmap example --- diff --git a/c/mmap-old/mmap.c b/c/mmap-old/mmap.c new file mode 100644 index 0000000..b2b1920 --- /dev/null +++ b/c/mmap-old/mmap.c @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +unsigned char *fmmap(FILE *fd) { + struct stat sb; + + if(!fd) perror(""); + fd = fileno(fd); + fstat((int)fd, &sb); + return mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, (int)fd, 0); +} + +int main() { + FILE *fd; + unsigned char *mm; + + fd = fopen("mmap.c", "r"); + mm = fmmap(fd); + + perror("Status"); + puts(mm); + + //munmap(mm, 10); + fclose(fd); +} diff --git a/c/mmap/mmap b/c/mmap/mmap deleted file mode 100755 index 061c1cc..0000000 Binary files a/c/mmap/mmap and /dev/null differ diff --git a/c/mmap/mmap.c b/c/mmap/mmap.c index b2b1920..69d5666 100644 --- a/c/mmap/mmap.c +++ b/c/mmap/mmap.c @@ -1,28 +1,26 @@ +//#define _GNU_SOURCE + #include -#include -#include -#include #include +#include +#include +#include +#include +#include -unsigned char *fmmap(FILE *fd) { - struct stat sb; - - if(!fd) perror(""); - fd = fileno(fd); - fstat((int)fd, &sb); - return mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, (int)fd, 0); -} +#define MEM_PATH "hello.bin" +#define MEM_SIZE 1048576 int main() { - FILE *fd; - unsigned char *mm; - - fd = fopen("mmap.c", "r"); - mm = fmmap(fd); + int fd; + fd = open(MEM_PATH, O_RDWR | O_SYNC | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR); + ftruncate(fd, MEM_SIZE); - perror("Status"); - puts(mm); + void *mem; + mem = mmap(NULL, MEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED , fd, 0); + close(fd); - //munmap(mm, 10); - fclose(fd); + char hello[] = "Hello!"; + memcpy(mem, hello, sizeof(hello)); + msync(mem, sizeof(hello), MS_SYNC); }