Answer the question
In order to leave comments, you need to log in
Working with sockets, how to remove/close correctly?
Hello!
Wrote an application and a systemd file. I start, everything is OK, it works. The application listens to a unix socket, nginx proxies into it. Everything is fine, but there is a small problem that scares: if the process sudo kill -9 {pid}
is killed, the goroutine that listens to the channel on os.Signal does not work, therefore the socket will not close. So, if someone kills the process, it will not start again:
listen unix /tmp/app.sock: bind: address already in use
Answer the question
In order to leave comments, you need to log in
The problem was that when os.Stat was requested, err was returned, and I checked it for os.IsExists(err)
, but if the file exists, then err will be nil. I changed it to !os.IsNotExists(err)
and it turned out to be removed via os.Remove("/tmp/app.sock")
var l net.Listener
var err error
l, err = net.Listen("unix", "/tmp/app.sock")
if err != nil {
log.Println(err)
if _, err := os.Stat("/tmp/app.sock"); !os.IsNotExist(err) {
log.Println("socket in use, trying to delete the socket")
err = os.Remove("/tmp/app.sock")
if err != nil {
log.Fatalln(err)
}
log.Println("socket file removed")
l, err = net.Listen("unix", "/tmp/app.sock")
if err != nil {
log.Fatalln(err)
}
}
}
defer l.Close()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question