代码功能:
调用posix的共享内存接口,写入和读取共享内存数据;
代码:
package main /* #cgo LDFLAGS: -lrt #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> */ import "C" import "unsafe" import "fmt" import "os" func main() { name := C.CString("testshm") defer C.free(unsafe.Pointer(name)) fd, err := C.shm_open(name, C.int(C.O_RDWR|C.O_CREAT), 0) if err != nil { fmt.Println(err.Error()) } fmt.Printf("fd:%d", int(fd)) ret, err := C.ftruncate(fd, 1024*1024) if err != nil || ret != 0 { fmt.Println("truncate failed.") os.Exit(1) } strTest := `hello, test write to shared memory` content := C.CString(strTest) res, err := C.write(fd, unsafe.Pointer(content), C.size_t(len(strTest))) if err != nil || res == -1 { fmt.Println("write to shared memory failed.") os.Exit(1) } C.lseek(fd, 0, C.SEEK_SET) //pRead := make([]byte, 100) pRead := C.malloc(100) defer C.free(pRead) bytesRead, err := C.read(fd, unsafe.Pointer(pRead), 100) if err != nil { fmt.Println(err.Error()) os.Exit(1) } fmt.Printf("bytes read :%d, str are:%s", bytesRead, string(C.GoBytes(pRead, 100))) C.getchar() C.shm_unlink(name) }
3. 注意引入的头文件注释行与golang的import代码行直接必须无空行;
有疑问加站长微信联系(非本文作者)