How do I use file descriptor 4 (or its equivalent) on Windows?

huangapple go评论80阅读模式
英文:

How do I use file descriptor 4 (or its equivalent) on Windows?

问题

我一直在编写一个作为Node.js一部分的子进程的Go服务器。

package main

import (
    "bufio"
    "encoding/json"
    "fmt"
    "os"
)

// IPC分隔符
const EOT byte = 3

func main() {
    // 监听stdin以接收从父进程发送的消息。
    reader := bufio.NewReader(os.Stdin)
    for {
        input, err := reader.ReadString(EOT)
        if err != nil {
            fmt.Printf("sockets: 无法从stdin读取:%v", err)
            if err == io.EOF {
                return
            }

            continue
        }

        // 去除EOT字节
        input = input[:len(input)-1]

        var payload Payload
        if err := json.Unmarshal([]byte(input), &payload); err != nil {
            fmt.Printf("sockets: 无法从stdin读取:%v", err)
            continue
        }
    }
}

然而,像这样使用stdin/stdout会阻止该代码段能够记录到控制台,因为父进程正在使用stdout的句柄。理想情况下,我会使用文件描述符4来实现这一点,以利用Node的使用方式,但唯一的问题是我对Windows的细节一无所知。我如何能够在Windows上使用与/dev/fd/4等效的IPC(如果有的话)?

PS:如果有更好的处理从stdin读取的方法,那也会对我有很大帮助。

英文:

I've been writing a Go server that acts as the child process of a chunk of Node.js.

package main

import (
    "bufio"
    "encoding/json"
    "fmt"
    "os"
)

// IPC delimiter
const EOT byte = 3

func main() {
	// Listen on stdin for messages sent from the parent process.
	reader := bufio.NewReader(os.Stdin)
	for {
		input, err := reader.ReadString(EOT)
		if err != nil {
			fmt.Printf("sockets: failed to read from stdin: %v", err)
			if err == io.EOF {
				return
			}

			continue
		}

        // Strip EOT bye
		input = input[:len(input) - 1]

		var payload Payload
		if err := json.Unmarshal([]byte(input), &payload); err != nil {
			fmt.Printf("sockets: failed to read from stdin: %v", err)
			continue
		}
	}
}

However, using stdin/stdout like this prevents this piece of the code from being able to log to console, as the parent process is using stdouts handle. Ideally I'd use file descriptor 4 for this to take advantage of how Node uses it, Only problem with this is I'm clueless with the nitty gritty details of Windows. How might I be able to use the equivalent (if any) of /dev/fd/4 for IPC on Windows?

PS: if there's a better way to handle reading from stdin, that would also help me a lot.

答案1

得分: 2

你可以尝试使用os.NewFile

f := os.NewFile(4, "my_fd_4")
英文:

You can try os.NewFile:

f := os.NewFile(4, "my_fd_4")

huangapple
  • 本文由 发表于 2016年11月25日 16:10:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/40800343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定