Skip to content

Instantly share code, notes, and snippets.

@alberts
Last active October 3, 2018 21:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alberts/4640792 to your computer and use it in GitHub Desktop.
Save alberts/4640792 to your computer and use it in GitHub Desktop.
package systemd
import (
"os"
"strconv"
"syscall"
)
const (
listenFdsStart = 3
)
func ListenFds() []*os.File {
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
if err != nil || pid != os.Getpid() {
return nil
}
nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
if err != nil || nfds == 0 {
return nil
}
files := []*os.File(nil)
for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
syscall.CloseOnExec(fd)
files = append(files, os.NewFile(uintptr(fd), ""))
}
return files
}
@nerdatmath
Copy link

Why run an extra fcntl system call just to find out whether you need to set the CLOEXEC flag? Just run syscall.CloseOnExec unconditionally. The result is the same, and you only run one system call per FD.

@alberts
Copy link
Author

alberts commented Jun 25, 2013

Good point. I just did a direct translation of sd_listen_fds long ago. I'll update this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment