Last active
December 20, 2015 19:19
-
-
Save asandroq/6182612 to your computer and use it in GitHub Desktop.
How to read from memory using a file descriptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/mman.h> | |
#include <sys/stat.h> /* For mode constants */ | |
#include <fcntl.h> /* For O_* constants */ | |
const char source[] = | |
"Generalized algebraic data types (GADTs) are a feature of functional " | |
"programming languages which generalize ordinary algebraic data types by " | |
"permitting value constructors to return special types. This article is " | |
"a tutorial about GADTs in Haskell programming language as they are " | |
"implemented by the Glasgow Haskell Compiler (GHC) as a language extension"; | |
int main(void) | |
{ | |
void *addr; | |
ssize_t size; | |
int fd, source_len; | |
source_len = strlen(source) + 1; | |
fd = shm_open("/alex", O_RDWR | O_CREAT | O_TRUNC, 0600); | |
printf("Got descriptor: %d\n", fd); | |
if(ftruncate(fd, source_len) < 0) | |
{ | |
perror("ftruncate"); | |
return 42; | |
} | |
if((addr = mmap(NULL, source_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) | |
{ | |
perror("mmap"); | |
return 42; | |
} | |
memcpy(addr, source, source_len); | |
if(munmap(addr, source_len) < 0) | |
{ | |
perror("munmap"); | |
return 42; | |
} | |
/* now the BIG test... reading from fd */ | |
addr = calloc(source_len, 1); | |
size = read(fd, addr, source_len); | |
printf("Sizes: %d, %d\n", source_len, size); | |
printf("Result: %s\n", addr); | |
free(addr); | |
close(fd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment