Source file src/os/exec/read3.go

     1  // Copyright 2020 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 ignore
     6  
     7  // This is a test program that verifies that it can read from
     8  // descriptor 3 and that no other descriptors are open.
     9  // This is not done via TestHelperProcess and GO_EXEC_TEST_PID
    10  // because we want to ensure that this program does not use cgo,
    11  // because C libraries can open file descriptors behind our backs
    12  // and confuse the test. See issue 25628.
    13  package main
    14  
    15  import (
    16  	"fmt"
    17  	"internal/poll"
    18  	"io"
    19  	"os"
    20  	"os/exec"
    21  	"os/exec/internal/fdtest"
    22  	"runtime"
    23  )
    24  
    25  func main() {
    26  	fd3 := os.NewFile(3, "fd3")
    27  	defer fd3.Close()
    28  
    29  	bs, err := io.ReadAll(fd3)
    30  	if err != nil {
    31  		fmt.Printf("ReadAll from fd 3: %v\n", err)
    32  		os.Exit(1)
    33  	}
    34  
    35  	// Now verify that there are no other open fds.
    36  	// stdin == 0
    37  	// stdout == 1
    38  	// stderr == 2
    39  	// descriptor from parent == 3
    40  	// All descriptors 4 and up should be available,
    41  	// except for any used by the network poller.
    42  	for fd := uintptr(4); fd <= 100; fd++ {
    43  		if poll.IsPollDescriptor(fd) {
    44  			continue
    45  		}
    46  
    47  		if !fdtest.Exists(fd) {
    48  			continue
    49  		}
    50  
    51  		fmt.Printf("leaked parent file. fdtest.Exists(%d) got true want false\n", fd)
    52  
    53  		fdfile := fmt.Sprintf("/proc/self/fd/%d", fd)
    54  		link, err := os.Readlink(fdfile)
    55  		fmt.Printf("readlink(%q) = %q, %v\n", fdfile, link, err)
    56  
    57  		var args []string
    58  		switch runtime.GOOS {
    59  		case "plan9":
    60  			args = []string{fmt.Sprintf("/proc/%d/fd", os.Getpid())}
    61  		case "aix", "solaris", "illumos":
    62  			args = []string{fmt.Sprint(os.Getpid())}
    63  		default:
    64  			args = []string{"-p", fmt.Sprint(os.Getpid())}
    65  		}
    66  
    67  		// Determine which command to use to display open files.
    68  		ofcmd := "lsof"
    69  		switch runtime.GOOS {
    70  		case "dragonfly", "freebsd", "netbsd", "openbsd":
    71  			ofcmd = "fstat"
    72  		case "plan9":
    73  			ofcmd = "/bin/cat"
    74  		case "aix":
    75  			ofcmd = "procfiles"
    76  		case "solaris", "illumos":
    77  			ofcmd = "pfiles"
    78  		}
    79  
    80  		cmd := exec.Command(ofcmd, args...)
    81  		out, err := cmd.CombinedOutput()
    82  		if err != nil {
    83  			fmt.Fprintf(os.Stderr, "%#q failed: %v\n", cmd, err)
    84  		}
    85  		fmt.Printf("%s", out)
    86  		os.Exit(1)
    87  	}
    88  
    89  	os.Stdout.Write(bs)
    90  }
    91  

View as plain text