D
D
danforth2017-06-23 22:45:14
linux
danforth, 2017-06-23 22:45:14

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

This scares me a little, I would not like to find that my server is throwing 502 errors at the most unexpected moment.
Here, in fact, the question is: what is the right thing to do in this case? Tried os.Remove("/tmp/app.sock") but writes that there is no such file. How to properly handle this situation, and indeed, in general, start the process if it was killed via kill -9?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
danforth, 2017-06-23
@danforth

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()

R
RidgeA, 2017-06-23
@RidgeA

No way.
Can't catch SIGKILL.
This is written at the very beginning of the docs https://golang.org/pkg/os/signal/.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question