dongtan5555 2017-12-05 01:28
浏览 283
已采纳

是否可以使用Go通过Unix域套接字发送和接收文件描述符?

In the unix(7) man page for Unix domain sockets, it says that sendmsg can be used with the SCM_RIGHTS flag to send file descriptors over these sockets. Is this supported in Go? Is there any good example code out there showing how it's done?

It appears that there is a Msghdr structure declared in the syscall package. But no functions take it. Maybe I have to use the raw system call interface?

  • 写回答

1条回答 默认 最新

  • dst3605528 2017-12-05 01:48
    关注

    There's a package that does it here: https://github.com/ftrvxmtrx/fd/blob/master/fd.go. However that's using the Syscall package to achieve it. I'm not sure if there's a way to do this with Go standard library API.

    In the syscall package, the things to look at are UnixRights, ParseUnixRights, and ParseSocketControlMessage. These can be used in conjunction with Readmsg and Sendmsg to send file descriptors over AF_UNIX sockets.

    The basic structure goes something like this for receiving:

    buf := make([]byte, syscall.CmsgSpace(<number of file descriptors expected> * 4))
    _, _, _, _, err = syscall.Recvmsg(socket, nil, buf, 0)
    if err != nil {
        panic(err)
    }
    var msgs []syscall.SocketControlMessage
    msgs, err = syscall.ParseSocketControlMessage(buf)
    var allfds []int
    for i := 0, i < len(msgs) && err == null; i++ {
        var msgfds []int
        msgfds, err = syscall.ParseUnixRights(&msgs[i])
        append(allfds, msgfds...)
    }
    

    And for sending, it's much simpler (var fds []int):

    rights := syscall.UnixRights(fds...)
    err := syscall.Sendmsg(socket, nil, rights, nil, 0)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?