I must missing something basic because the following is not working as expected.
go run test_fd.go <(cat)
under either bash or zsh results in the following:
Expected output
$ go run test_fd.go <(cat) # where n is some fd number
fd {{n}} filename /dev/fd/{{n}}
Hello!
Actual output (Zsh)
$ go run test_fd.go <(cat)
fd 11 filename /dev/fd/11
panic: Write() err write /dev/fd/11: bad file descriptor
goroutine 1 [running]:
panic(0xefe80, 0xc820010200)
/usr/local/Cellar/go/1.6/libexec/src/runtime/panic.go:464 +0x3e6
main.main()
/Users/bmf/Projects/piper/main.go:32 +0x515
exit status 2
Actual output (Bash)
$ go run main.go <(cat)
fd 63 filename /dev/fd/63
panic: Write() err write /dev/fd/63: bad file descriptor
goroutine 1 [running]:
panic(0xefe80, 0xc82006c240)
/usr/local/Cellar/go/1.6/libexec/src/runtime/panic.go:464 +0x3e6
main.main()
/Users/bmf/Projects/piper/main.go:32 +0x515
exit status 2
Source
// test_fd.go
package main
import (
"fmt"
"os"
"regexp"
"strconv"
)
var fdRegex = regexp.MustCompile(`\A/dev/fd/(\d+)\z`)
func main() {
for _, filename := range os.Args {
fdStrMatch := fdRegex.FindStringSubmatch(filename)
if len(fdStrMatch) != 2 {
continue
}
fd, _ := strconv.Atoi(fdStrMatch[1]) // fdStrMatch[1] is \d+
fmt.Fprintf(os.Stderr, "fd %d filename %s
", fd, filename)
f := os.NewFile(uintptr(fd), filename)
/*
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0777) // have tried many combinations of modes
if err != nil {
panic(fmt.Sprintf("Create() err %v", err))
}
*/
_, err := f.Write([]byte("Hello!
"))
if err != nil {
panic(fmt.Sprintf("Write() err %v", err))
}
}
}