github.com/cilium/ebpf@v0.10.0/internal/sys/fd_test.go (about) 1 package sys 2 3 import ( 4 "os" 5 "syscall" 6 "testing" 7 8 "github.com/cilium/ebpf/internal/unix" 9 qt "github.com/frankban/quicktest" 10 ) 11 12 func init() { 13 // Free up fd 0 for TestFD. 14 stdin, err := unix.FcntlInt(os.Stdin.Fd(), unix.F_DUPFD_CLOEXEC, 1) 15 if err != nil { 16 panic(err) 17 } 18 19 old := os.Stdin 20 os.Stdin = os.NewFile(uintptr(stdin), "stdin") 21 old.Close() 22 23 reserveFdZero() 24 } 25 26 func reserveFdZero() { 27 fd, err := unix.Open(os.DevNull, syscall.O_RDONLY, 0) 28 if err != nil { 29 panic(err) 30 } 31 if fd != 0 { 32 panic(err) 33 } 34 } 35 36 func TestFD(t *testing.T) { 37 _, err := NewFD(-1) 38 qt.Assert(t, err, qt.IsNotNil, qt.Commentf("negative fd should be rejected")) 39 40 fd, err := NewFD(0) 41 qt.Assert(t, err, qt.IsNil) 42 qt.Assert(t, fd.Int(), qt.Not(qt.Equals), 0, qt.Commentf("fd value should not be zero")) 43 44 var stat unix.Stat_t 45 err = unix.Fstat(0, &stat) 46 qt.Assert(t, err, qt.ErrorIs, unix.EBADF, qt.Commentf("zero fd should be closed")) 47 48 reserveFdZero() 49 }