英文:
Failsafe way of listening on a unix-domain-socket
问题
这段代码在第一次运行时正常工作:
package main
import (
"context"
"fmt"
"net"
)
func main() {
ctx := context.Background()
udsName := "dummy.socket"
var lc net.ListenConfig
_, err := lc.Listen(ctx, "unix", udsName)
if err != nil {
panic(fmt.Sprintf("failed to listen(unix) name %s: %v", udsName, err))
}
fmt.Println("all is fine")
}
但在第二次运行时失败:
panic: failed to listen(unix) name dummy.socket: listen unix dummy.socket: bind: address already in use
我可以在Listen()
之前删除文件,但如果已经有一个进程在监听此套接字上,这可能会导致失败。
有没有办法检测是否有进程在监听该套接字?
然后,如果旧服务器已经停止运行,我可以删除旧的dummy.socket文件。
英文:
This code works fine on the first run:
package main
import (
"context"
"fmt"
"net"
)
func main() {
ctx := context.Background()
udsName := "dummy.socket"
var lc net.ListenConfig
_, err := lc.Listen(ctx, "unix", udsName)
if err != nil {
panic(fmt.Sprintf("failed to listen(unix) name %s: %v", udsName, err))
}
fmt.Println("all is fine")
}
But it fails on the second run:
> panic: failed to listen(unix) name dummy.socket: listen unix dummy.socket: bind: address already in use
I could just remove the file before Listen()
, but this could be a failure, if there is already a process listening on this socket.
Is there a way to detect if there is a process listening on the socket?
Then I could remove the old dummy.socket file, if the old server is dead.
答案1
得分: 2
在绑定之前删除Unix套接字文件,这是我知道的唯一“安全”的方法:
package main
import (
"context"
"fmt"
"net"
)
func main() {
ctx := context.Background()
udsName := "dummy.socket"
os.Remove(udsName) //删除Unix套接字文件
var lc net.ListenConfig
_, err := lc.Listen(ctx, "unix", udsName)
if err != nil {
panic(fmt.Sprintf("无法侦听(unix)名称%s:%v", udsName, err))
}
fmt.Println("一切正常")
}
英文:
Delete the unix socket file prior to binding, only 'failsafe' way i know:
package main
import (
"context"
"fmt"
"net"
)
func main() {
ctx := context.Background()
udsName := "dummy.socket"
os.Remove(udsName) //delete the unix socket file
var lc net.ListenConfig
_, err := lc.Listen(ctx, "unix", udsName)
if err != nil {
panic(fmt.Sprintf("failed to listen(unix) name %s: %v", udsName, err))
}
fmt.Println("all is fine")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论