This is a creation in Article, where the information may have evolved or changed.
Code Features:
Invokes a POSIX shared memory interface to write and read shared memory data;
Code:
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 (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. Note that the imported header file Comment line and the import code line of the Golang must have no blank line directly;