here is my code
shmid, _, err := syscall.Syscall(syscall.SYS_SHMGET, uintptr(10001), 1<<32, IpcCreate|0600)
data_shmaddr, _, _ := syscall.Syscall(syscall.SYS_SHMAT, shmid, 0, 0)
C.memcpy(unsafe.Pointer(data_shmaddr+uintptr(per_offs)), unsafe.Pointer((C.CString)(string(*data))), C.ulong(len(*data)))
i want to copy ‘data’ to sharememory with memcpy, but it seems like i can’t map all the address from data_shmaddr to (data_shmaddr+1<<32).
here is what i got:
fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x7fe3502cca80 pc=0x7fe34d9320b4]
It may help if you show us a complete program, rather than just a snippet. What are you using for IpcCreate? How did you declare data?
Without knowing those, I worked with your example. I have this:
package main
//#include <stdio.h>
//#include <string.h>
//#include <sys/ipc.h>
//#include <sys/shm.h>
//void *memcpy(void *dest, const void *src, size_t n);
//int printf(const char *format, ...);
//#define BUFSIZE 32
//void dump(char *p)
//{
// int i;
// for(i = 0; i < BUFSIZE; i++)
// printf("%d: %d\n",i,p[i]);
// printf("\n");
//}
import "C"
import (
"fmt"
"os"
"syscall"
"unsafe"
)
const bufsize int = 32
const offset = 10
var IpcCreate uintptr
var per_offs int = offset
var buf [bufsize]byte
var data *[bufsize]byte
// a tag so we can recognize if it's copying properly
const tagsize int = 10
const tag byte = 42
func main() {
data = &buf
IpcCreate = C.IPC_CREAT
shmid, _, err := syscall.Syscall(syscall.SYS_SHMGET, uintptr(10001), 1<<32, IpcCreate|0600)
if err != 0 {
fmt.Fprintf(os.Stderr,"Cannot get shared memory. Error %d\n", err)
os.Exit(1)
}
data_shmaddr, _, err := syscall.Syscall(syscall.SYS_SHMAT, shmid, 0, 0)
if err != 0 {
fmt.Fprintf(os.Stderr,"Cannot attach to shared memory. Error %d\n", err)
os.Exit(1)
}
// write the tag into the buffer
for i := 0; i < tagsize; i++ { buf[i] = tag }
// copy the buffer into the shared memory, starting at byte 10
C.memcpy(unsafe.Pointer(data_shmaddr+uintptr(per_offs)),
unsafe.Pointer(data), C.ulong(len(*data)))
// dump data[]
// this shows that 42 is in locations 0-9
fmt.Printf("\n")
fmt.Printf("data:\n")
C.dump(C.CString(string((*data)[:])))
// dump bufsize bytes of shared memory area
// this shows that 42 is in locations 10-19
fmt.Printf("shared memory:\n")
C.dump((*C.char)(unsafe.Pointer(uintptr(data_shmaddr))))
}
I think this does what you want it to. If not, then please state your problem more clearly.
Note to everyone: This program uses Cgo and both the unsafe and syscall packages. So don’t expect it to be cross-platform. If you have Linux, you can try it.