golang.org/x/sys@v0.20.1-0.20240517151509-673e0f94c16d/unix/dup3_test.go (about) 1 // Copyright 2023 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 5 //go:build freebsd || linux || netbsd || openbsd 6 7 package unix_test 8 9 import ( 10 "os" 11 "path/filepath" 12 "runtime" 13 "testing" 14 15 "golang.org/x/sys/unix" 16 ) 17 18 func TestDup3(t *testing.T) { 19 tempFile, err := os.Create(filepath.Join(t.TempDir(), "TestDup")) 20 if err != nil { 21 t.Fatal(err) 22 } 23 defer tempFile.Close() 24 oldFd := int(tempFile.Fd()) 25 26 // On NetBSD, it is not an error if oldFd == newFd 27 if runtime.GOOS != "netbsd" { 28 if got, want := unix.Dup3(oldFd, oldFd, 0), unix.EINVAL; got != want { 29 t.Fatalf("Dup3: expected err %v, got %v", want, got) 30 } 31 } 32 33 // Create and reserve a file descriptor. 34 // Dup3 automatically closes it before reusing it. 35 nullFile, err := os.Open("/dev/null") 36 if err != nil { 37 t.Fatalf("Open failed: %v", err) 38 } 39 defer nullFile.Close() 40 newFd := int(nullFile.Fd()) 41 42 err = unix.Dup3(oldFd, newFd, 0) 43 if err != nil { 44 t.Fatalf("Dup3: %v", err) 45 } 46 47 b1 := []byte("Test123") 48 b2 := make([]byte, 7) 49 _, err = unix.Write(newFd, b1) 50 if err != nil { 51 t.Fatalf("Write to Dup3 fd failed: %v", err) 52 } 53 _, err = unix.Seek(oldFd, 0, 0) 54 if err != nil { 55 t.Fatalf("Seek failed: %v", err) 56 } 57 _, err = unix.Read(oldFd, b2) 58 if err != nil { 59 t.Fatalf("Read back failed: %v", err) 60 } 61 if string(b1) != string(b2) { 62 t.Errorf("Dup3: read %q from file, want %q", string(b2), string(b1)) 63 } 64 }