tmpfile_linux.go 762 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. //go:build linux
  2. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  3. package utils
  4. import (
  5. "fmt"
  6. "os"
  7. "strconv"
  8. "golang.org/x/sys/unix"
  9. )
  10. var _ = fmt.Print
  11. func CreateAnonymousTemp(dir string) (*os.File, error) {
  12. if dir == "" {
  13. dir = os.TempDir()
  14. }
  15. fd, err := unix.Open(dir, unix.O_RDWR|unix.O_TMPFILE|unix.O_CLOEXEC, 0600)
  16. if err == nil {
  17. path := "/proc/self/fd/" + strconv.FormatUint(uint64(fd), 10)
  18. return os.NewFile(uintptr(fd), path), nil
  19. }
  20. if err == unix.ENOENT {
  21. return nil, &os.PathError{
  22. Op: "open",
  23. Path: dir,
  24. Err: err,
  25. }
  26. }
  27. f, err := os.CreateTemp(dir, "")
  28. if err != nil {
  29. return nil, err
  30. }
  31. err = os.Remove(f.Name())
  32. if err != nil {
  33. f.Close()
  34. return nil, err
  35. }
  36. return f, err
  37. }