I heard the slogan in golang about shared memory via communication, but here I have a need to write an application to interact with an existing application A using shared memory. Basically A writes a big chunk of data in memory (so big that it's inefficient to other other means of IPC), and wait for a program B to process it and report the result to A.
Would like to write the program B using golang due to its scriptability and speed, but don't see the direct support for shared memory. Thought of using C interface in golang but there is a problem with passing pointers between the two languages.
Any ideas? Thanks!
UPDATE1: Forgot to mention this is on Ubuntu 12.04. Thanks for asking.
UPDATE2: Created a simple program to test the reading of data pointed to by C pointer.
golang code called "reader.go"
import "C"
import "unsafe"
import "fmt"
func read(filename string) string {
f := C.CString(filename)
defer C.free(unsafe.Pointer(f))
s := C.testc(f)
defer C.free(unsafe.Pointer(s))
return C.GoString(s)
}
func main() {
fmt.Println(read("tmp"))
}
C code called wrapper.c
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
char buf[0x10000];
char* testc(char* filename){
printf("reading file %s
", filename);
FILE *fp = fopen(filename, "r");
fread(buf, 1, 100, fp);
fclose(fp);
return buf;
}
When running go run reader.go
, got a stackdump on go (too long to include here).
UPDATE 3:
Find the line that caused go to crash: defer C.free(unsafe.Pointer(s))
Without it, things works fine.
Credit: the code snippet is adapted from https://gist.github.com/jedy/3282764.
I take it that you are referring to System V IPC shared memory. There is a good post in golang-nuts about how to go about implementing System V IPC semaphores, and much of this would also apply to the shm system calls.
You can use CGO, but it is generally better to write pure Go functions that call the UNIX system calls directly. The package at golang.org/x/sys/unix contains many good examples of how to invoke system calls from Go without having to involve CGO. (If you do go down this path, it would be a great idea to create a CL to update that package).