Skip to content

Instantly share code, notes, and snippets.

@cavaliercoder
Last active May 7, 2016 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cavaliercoder/68bb2ee0d673cb3d585199fe189fb171 to your computer and use it in GitHub Desktop.
Save cavaliercoder/68bb2ee0d673cb3d585199fe189fb171 to your computer and use it in GitHub Desktop.
Go runtime misbehaves in forked processes
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
#include <errno.h>
typedef void (*golib_func)(void);
int main() {
int i;
for (i = 0; i < 5; i++) {
if (0 == fork()) {
// load lib and func symbol
void *golib = NULL;
golib_func f;
printf("Start child %i (%i)\n", i, getpid());
if (NULL != (golib = dlopen("./golib.so", RTLD_NOW|RTLD_NODELETE))) {
if (NULL != (f = dlsym(golib, "TestNetDial"))) {
for(i = 0; i < 10; i++)
(*f)();
} else {
printf("%s\n", dlerror());
}
dlclose(golib);
} else {
printf("%s\n", dlerror());
}
exit(0);
}
}
for (i = 0; i < 5; i++)
wait(NULL);
}
package main
import "C"
import (
"fmt"
"net"
"os"
)
func main() {
// nothing to do here
}
//export TestNetDial
func TestNetDial() {
conn, err := net.Dial("tcp", "golang.org:443")
if err != nil {
panic(err)
}
defer conn.Close()
fmt.Printf("--> Connected to %s in PID %v\n", conn.RemoteAddr(), os.Getpid())
}
all: cbin golib.so
cbin: cbin.c
gcc -ldl -o cbin cbin.c
golib.so: golib.go
go build -x -buildmode=c-shared -o golib.so golib.go
clean:
rm -vf cbin golib.so
.PHONY: all clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment