dongluzhi5208 2013-06-19 13:52
浏览 71
已采纳

如何安全地将net.Listener()的FD传递给子进程?

I've been stucked with this issue for hours:

I have a main process served as a TCP server, the main process call Fork(), pass its net.Listener()'s FD to child process. Then child process can use net.Filelistener() to inherit this FD.

I have researched this issue through many open-sourced codes, also did some experiments. But unfortunately none of these solutions satisfy me for now since they are not portable, you also need many low-level jobs which are dangerous.

If there's any solution to pass net.Listener()'s FD to child process SAFELY, I'd be glad to know.

What I've tried for now:

  1. Environment values, not portable, will cause chaos with many FDs, not safe since can be changed from outside.

  2. Dup FD & Clear FD_CLOEXEC then exec/fork, portable but not supported by Go API, a syscall.NoCloseOnExec() change submitted to dev team was rejected since they want to keep syscall clean.

  3. Set SO_REUSEADDR so child process can listen to port instantly, close parent's listener before that. Failed, not portable, not supported by Go API, also unsafe.

  4. exec.Command.ExtraFiles(), have no idea how to get inherited FDs from child process, do I need a config file to save FD & names? This solution also have a bug, read exec's document for more detail.

All right guys, I've written a simple test case of this issue(with solution 4):

https://github.com/reckhou/go-fd-pass-test

Also include 2 executables on OS X & Linux. I tried Go 1.1 & Go 1.1.1 but this issue still remains.

  • 写回答

2条回答 默认 最新

  • dora12345678 2013-06-19 18:00
    关注

    The easiest way is to pass the listener in the ExtraFiles field of exec.Cmd.

    Example of parent:

    var l *net.TCPListener
    cmd := exec.Command(...)
    f, err := l.File()
    cmd.ExtraFiles = []*os.File{f}
    

    Example of child:

    l, err := net.FileListener(os.NewFile(3, "listener"))
    

    You may also want to generalize this and have the child accept PROGRAMNAME_LISTENER_FD as an environment variable. Then the parent would set the environment variable to 3 before starting the child.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿