如何在golang中向已打开的文件描述符(FD)写入数据

huangapple go评论156阅读模式
英文:

How to write to already opened FD in golang

问题

我有以下打开的文件描述符(lsof输出):

auth    11780 root    5w  FIFO               0,10      0t0  72061824 pipe

我需要在Go语言中向文件描述符5(FIFO)写入内容。在C语言中,可以使用syscall write()函数来实现:

19270 write(5, "*************", 12 <unfinished ...>

提前谢谢!

英文:

I have the following opened FD (lsof output):

auth    11780 root    5w  FIFO               0,10      0t0  72061824 pipe

I need to write something in FD 5 (FIFO) in go. In C it is performed by the syscall write():

19270 write(5, &quot;*************&quot;, 12 &lt;unfinished ...&gt;

Thank you in advance!

答案1

得分: 8

使用os.NewFile通过文件描述符来“打开”一个已存在的文件:

> func NewFile(fd uintptr, name string) *File
> NewFile函数返回一个具有给定文件描述符和名称的新文件。

file := os.NewFile(5, "pipe")
_, err := file.Write([]byte(`my data`))
if err != nil {
    panic(err)
}
英文:

Use os.NewFile to "open" an existing file by its file descriptor:

> func NewFile(fd uintptr, name string) *File
> NewFile returns a new File with the given file descriptor and name.

file := os.NewFile(5, &quot;pipe&quot;)
_, err := file.Write([]byte(`my data`))
if err != nil {
    panic(err)
}

huangapple
  • 本文由 发表于 2017年7月3日 20:53:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/44886135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定