-
-
Save jedy/3037240 to your computer and use it in GitHub Desktop.
在golang中传递网络socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
s.go 是要启动的子进程, uintptr(3) 代表了从父进程传过来的 pipe 序号,0 是 stdin, 1 是 stdout, 2 是 stderr ;自然 3 就是 t.go L35 所传进来的 conn 对应的文件了