executable_procfs.go 936 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build hurd || linux || netbsd || (js && wasm)
  5. package os
  6. import (
  7. "errors"
  8. "runtime"
  9. )
  10. func executable() (string, error) {
  11. var procfn string
  12. switch runtime.GOOS {
  13. default:
  14. return "", errors.New("Executable not implemented for " + runtime.GOOS)
  15. case "hurd", "linux", "android":
  16. procfn = "/proc/self/exe"
  17. case "netbsd":
  18. procfn = "/proc/curproc/exe"
  19. }
  20. path, err := Readlink(procfn)
  21. // When the executable has been deleted then Readlink returns a
  22. // path appended with " (deleted)".
  23. return stringsTrimSuffix(path, " (deleted)"), err
  24. }
  25. // stringsTrimSuffix is the same as strings.TrimSuffix.
  26. func stringsTrimSuffix(s, suffix string) string {
  27. if len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix {
  28. return s[:len(s)-len(suffix)]
  29. }
  30. return s
  31. }