gpt4 book ai didi

go - 拨 unixgram : no such file or directory error

转载 作者:IT王子 更新时间:2023-10-29 02:20:42 29 4
gpt4 key购买 nike

我编写了一个与 wpa_supplicant 对话的小型库。我已经验证它适用于测试应用程序,但我也想添加一个单元测试。我的单元测试无法连接到 unix 套接字。我收到错误“没有这样的文件或目录”,但两个套接字文件都已创建。

lib.go

package libwpa

import (
"bytes"
"fmt"
"io/ioutil"
"net"
"os"
"strconv"
"strings"
)

type Conn struct {
uconn *net.UnixConn //Linux specific
localSock *os.File
}

func Connect(usock string) (*Conn, error) {
var (
uc *Conn
err error
)
uc = &Conn{}

if uc.localSock, err = ioutil.TempFile("/tmp", "wpa_supplicant"); err != nil {
return uc, err
}
os.Remove(uc.localSock.Name())

uc.uconn, err = net.DialUnix("unixgram",
&net.UnixAddr{Name: uc.localSock.Name(), Net: "unixgram"},
&net.UnixAddr{Name: usock, Net: "unixgram"})
if err != nil {
return uc, err
}

return uc, nil
}

lib_test.go

package libwpa

import (
"fmt"
"io/ioutil"
"net"
"os"
"testing"
)

func listen(reply chan<- []byte) {
conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: "/tmp/foobar", Net: "unixgram"})
if err != nil {
fmt.Printf("failed to listen: %v\n", err)
panic(err)
}
defer os.Remove("/tmp/foobar")

f, _ := ioutil.ReadDir("/tmp")
for _, d := range f {
fmt.Printf("%v\n", d.Name())
}

buf := make([]byte, 2048)
n, uaddr, err := conn.ReadFromUnix(buf)
if err != nil {
fmt.Printf("LISTEN: Error: %v\n", err)
} else {
fmt.Printf("LISTEN: received %v bytes from %+v\n", n, uaddr)
fmt.Printf("LISTEN: %v\n", string(buf))
}

conn.Close()
reply <- buf
}

func Test_Connect(t *testing.T) {
reply := make(chan []byte, 2)
go listen(reply)
_, err := Connect("/tmp/foobar")
if err != nil {
t.Fatalf("Failed to connect: %v", err)
}
}

运行得到

$ go test                                                                                                                                                                                                                                                    
--- FAIL: Test_Connect (0.00s)
lib_test.go:42: Failed to connect: dial unixgram /tmp/wpa_supplicant208023735->/tmp/foobar: connect: no such file or directory
FAIL
exit status 1
FAIL _/home/code/apps/go/src/crown/libwpa 0.006s

$ ls /tmp/{foobar,wpa*}
/tmp/foobar= /tmp/wpa_supplicant923064975=

最佳答案

我想你之前忘了加上“defer”关键字:

os.Remove(uc.localSock.Name())

在你的 lib.go 文件中。修复后,您将收到“地址已在使用”错误。

关于go - 拨 unixgram : no such file or directory error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51024502/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com