Package ipc provides a way to use System V IPC. System V IPC includes three interprocess communication mechanisms that are widely available on UNIX systems: message queues, semaphore, and shared memory.
package mainimport ("encoding/binary""flag""fmt""github.com/hslam/ipc""os""os/signal""syscall")varsend=flag.Bool("s",true,"send")funcmain() {flag.Parse()key,_:=ipc.Ftok("/tmp",0x22)semnum:=0semid,err:=ipc.Semget(key,1,0666)iferr!=nil {semid,err=ipc.Semget(key,1,ipc.IPC_CREAT|ipc.IPC_EXCL|0666)iferr!=nil {panic(err)}_,err:=ipc.Semsetvalue(semid,semnum,1)iferr!=nil {panic(err)}}deferipc.Semrm(semid)shmid,data,_:=ipc.Shmgetattach(key,128,ipc.IPC_CREAT|0600)deferipc.Shmrm(shmid)deferipc.Shmdetach(data)msgid,_:=ipc.Msgget(key,ipc.IPC_CREAT|0600)deferipc.Msgrm(msgid)vartextstringquit:=make(chan os.Signal)signal.Notify(quit,syscall.SIGINT,syscall.SIGTERM)gofunc() {deferclose(quit)if*send {fmt.Println("Enter:")buf:=make([]byte,10)for {fmt.Scanln(&text)if_,err:=ipc.Semp(semid,semnum,ipc.SEM_UNDO);err!=nil {return}copy(data,text)if_,err:=ipc.Semv(semid,semnum,ipc.SEM_UNDO);err!=nil {return}n:=binary.PutUvarint(buf,uint64(len(text)))iferr:=ipc.Msgsend(msgid,1,buf[:n],0600);err!=nil {return}}}else {fmt.Println("Recv:")for {m,err:=ipc.Msgreceive(msgid,1,0600)iferr!=nil {return}length,_:=binary.Uvarint(m)if_,err:=ipc.Semp(semid,semnum,ipc.SEM_UNDO);err!=nil {return}text=string(data[:length])if_,err:=ipc.Semv(semid,semnum,ipc.SEM_UNDO);err!=nil {return}fmt.Println(text)}}}()<-quit}
Enter a word.
In another terminal receive this word.
ipc was written by Meng Huang.