examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

commit b85fe016df137f5a661738d397167e6c6400afbc
parent 94a2185f3e15a7e6a3b0abed8baca35d5b959d41
Author: Henry Wilson <henry@henryandlizzy.uk>
Date:   Wed, 15 Feb 2023 22:42:24 +0000

mremap: Add growable fixed memory address buffer example

Diffstat:
Msrc/morse.c | 24++++++++++++++++--------
Asrc/mremap.c | 31+++++++++++++++++++++++++++++++
2 files changed, 47 insertions(+), 8 deletions(-)

diff --git a/src/morse.c b/src/morse.c @@ -8,12 +8,12 @@ void put_morse_char(unsigned dit) void put_morse_seq(unsigned seq) { - putchar(' '); while (seq > 1) { put_morse_char(seq & 1); seq >>= 1; } + putchar(' '); } unsigned char seqs[] = @@ -84,11 +84,17 @@ unsigned char seqs[] = void put_morse(char c) { - unsigned char m = seqs[toupper(c)]; - if (m) - put_morse_seq(m); - else - putchar('\n'); + switch (c) + { + case ' ': + case '\n': + putchar(c); + break; + default: + unsigned char m = seqs[toupper(c)]; + if (m) + put_morse_seq(m); + } } void put_morse_str(char const* str) @@ -102,11 +108,13 @@ int main() for (;;) { int c = getchar(); - if (c <= 0) + if (c == EOF) break; + if (c >= (int)sizeof(seqs)) + return 1; put_morse(c); } - putchar ('\n'); +// putchar ('\n'); return 0; } diff --git a/src/mremap.c b/src/mremap.c @@ -0,0 +1,31 @@ +#define _GNU_SOURCE +#include <sys/mman.h> +#include <stdlib.h> +#include <stdio.h> + +int main() +{ + unsigned long long* mem; + size_t size = 0x1000; + mem = mmap((void*)0x1000000, size, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); + + unsigned i; + for (i = 0; i < 0x1000; ++i) + { + if (i * sizeof (*mem) >= size) + { + if(mem != mremap(mem, size, size * 2, 0)) + exit(1); + size = size*2; + } + mem[i] = i % 256; + } + + unsigned long long total = 0; + + while (i--) + total += mem[i]; + printf("total = %llx\n", total); + + munmap(mem, size); +}