Skip to content

Instantly share code, notes, and snippets.

@earoc
Forked from jedy/s.go
Created May 14, 2019 05:15
Show Gist options
  • Select an option

  • Save earoc/d2b24346bda6e5765f10e9d588639a27 to your computer and use it in GitHub Desktop.

Select an option

Save earoc/d2b24346bda6e5765f10e9d588639a27 to your computer and use it in GitHub Desktop.
在golang中传递网络socket
package main
import (
"fmt"
"net"
"os"
"bufio"
)
func main() {
file := os.NewFile(uintptr(3), "tcp") // 0,1,2是标准输入,输出,错误输出。传进来的fd从3开始
c, err := net.FileConn(file)
if err != nil {
fmt.Println(err)
}
file.Close()
writer := bufio.NewWriter(c)
writer.WriteString("hello world\n")
writer.Flush()
c.Close()
}
package main
import (
"fmt"
"net"
"syscall"
"os"
)
func listen() {
ln, err := net.Listen("tcp", ":9999")
if err != nil {
panic(err)
}
tcpln := ln.(*net.TCPListener)
for {
c, err := tcpln.AcceptTCP()
if err != nil {
fmt.Println(err)
break
}
if err != nil {
fmt.Println(err)
break
}
go handleConn(c)
}
}
func handleConn(c *net.TCPConn) {
file, _ := c.File()
defer file.Close()
defer c.Close()
syscall.CloseOnExec(int(file.Fd())) // 设置关闭文件只对当前进程有效
allFiles := []*os.File{os.Stdin, os.Stdout, os.Stderr, file, nil}
wd, _ := os.Getwd()
_, err := os.StartProcess("s", nil, &os.ProcAttr{
Dir: wd,
Files: allFiles,
})
if err != nil {
fmt.Println(err)
}
}
func main() {
listen()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment