Created
November 27, 2015 07:11
-
-
Save siburu/e276cb52ec57eb16c479 to your computer and use it in GitHub Desktop.
Call syscalls in Golang
This file contains 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" | |
"log" | |
"syscall" | |
) | |
const filePath = "data.dat" | |
func main() { | |
// unlink(2) | |
err := syscall.Unlink(filePath) | |
if err != nil && err != syscall.ENOENT { | |
log.Fatalf("syscall.Unlink: %v\n", err) | |
} | |
// open(2) | |
fd, err := syscall.Open(filePath, | |
syscall.O_CREAT|syscall.O_EXCL|syscall.O_RDWR, | |
0) | |
if err != nil { | |
log.Fatalf("syscall.Open: %v\n", err) | |
} | |
fmt.Printf("fd=%d\n", fd) | |
// write(2) | |
_, err = syscall.Write(fd, make([]byte, 4096)) | |
if err != nil { | |
log.Fatalf("syscall.Write: %v\n", err) | |
} | |
// mmap(2) | |
data, err := syscall.Mmap(fd, 0, 4096, | |
syscall.PROT_READ|syscall.PROT_WRITE, | |
syscall.MAP_SHARED) | |
if err != nil { | |
log.Fatalf("syscall.Mmap: %v\n", err) | |
} | |
// close(2) | |
err = syscall.Close(fd) | |
if err != nil { | |
log.Fatalf("syscall.Close: %v\n", err) | |
} | |
fmt.Printf("len(data)=%d\n", len(data)) | |
fmt.Printf("cap(data)=%d\n", cap(data)) | |
for i := 0; i < len(data); i++ { | |
data[i] = 'x' | |
} | |
// munmap(2) | |
err = syscall.Munmap(data) | |
if err != nil { | |
log.Fatalf("syscall.Munmap: %v\n", err) | |
} | |
fmt.Println("Done.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment