identical mmap programs in C and go
-
-
Save MilosSimic/fdcccd483650aae601a13230d38b328c to your computer and use it in GitHub Desktop.
mmap examples
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 <unistd.h> | |
#include <fcntl.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <sys/mman.h> | |
int main () { | |
const char* filename = "main.c"; | |
int offset = 10; | |
int fd = open(filename, O_RDONLY); | |
if (fd == -1) { | |
printf("cannot open %s\n", filename); | |
return -1; | |
} | |
struct stat sbuf; | |
if (stat(filename, &sbuf) == -1) { | |
printf("cannot stat %s\n", filename); | |
return -1; | |
} | |
int size = sbuf.st_size; | |
char* data = mmap((caddr_t)0, size, PROT_READ, MAP_SHARED, fd, 0); | |
if (data == -1) { | |
printf("cannot mmap %s\n", filename); | |
return -1; | |
} | |
printf("byte at offset %d is %c\n", offset, data[offset - 1]); | |
int err = munmap(data, size); | |
if (err == -1) { | |
printf("cannot munmap %s\n", filename); | |
return -1; | |
} | |
return 0; | |
} |
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
package main | |
import ( | |
"fmt" | |
"os" | |
"syscall" | |
) | |
func main() { | |
filename, offset := "main.c", 10 | |
f, err := os.Open(filename) | |
if err != nil { | |
panic(err) | |
} | |
fd := int(f.Fd()) | |
stat, err := f.Stat() | |
if err != nil { | |
panic(err) | |
} | |
size := int(stat.Size()) | |
b, err := syscall.Mmap(fd, 0, size, syscall.PROT_READ, syscall.MAP_SHARED) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("%c\n", b[offset-1]) | |
err = syscall.Munmap(b) | |
if err != nil { | |
panic(err) | |
} | |
} |
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
package main | |
import ( | |
"os" | |
"syscall" | |
) | |
func main() { | |
filename, offset, length := "testgo.out", 10, 20 | |
f, err := os.Create(filename) | |
if err != nil { | |
panic(err) | |
} | |
f.Write(make([]byte, length)) | |
fd := int(f.Fd()) | |
b, err := syscall.Mmap(fd, 0, length, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED) | |
if err != nil { | |
panic(err) | |
} | |
b[offset-1] = 'x' | |
err = syscall.Munmap(b) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment