duangu6588 2016-03-19 14:06
浏览 32

如何在Go中输出到流程替换文件?

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))
    }
  }
}
  • 写回答

1条回答 默认 最新

  • dongzhanlu0658 2016-03-19 14:31
    关注

    Wrong form of process substitution:

    $ go run test_fd.go >(cat)

    • <(...) is read-only from the process via some file, usually /dev/fd/*
    • >(...) is write-only from the process via some file usually /dev/fd/*
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度