我试图让两个golang程序使用管道进行通信,每个程序同时运行,例如:
1 go run master/main/main.go
2 master/main/main.go calls slave.exe (built go program)
3 slave.exe prints out "Ping"
4 master/main/main.go reads "Ping" and writes "Pong"
5 slave.exe reads "Pong" and prints out "Message recieved: Pong"
程序到达步骤4但它没有收到来自slave.exe的另一条消息。
在master / main / main.go中:
package main
import (
"fmt"
"os"
"os/exec"
"bufio"
)
func main() {
// Run compiled slave project:
c := exec.Command("main", insert_path_to_exe_here)
out, _ := c.StdoutPipe()
in, _ := c.StdinPipe()
c.Start() // Using Start() instead of Run() because Run() waits for program to finish before moving on.
inwriter := bufio.NewWriter(in)
outreader := bufio.NewReader(out)
// This should print "Ping".
fmt.Println(outreader.ReadString('\n'))
inwriter.WriteString("Pong")
// This should print "Message received: Pong"
fmt.Println(outreader.ReadString('\n'))
}
在slave / main / main.go中:
package main
import (
"fmt"
"bufio"
"os"
)
func main() {
fmt.Println("Ping")
reader := bufio.NewReader(os.Stdin)
s, _ := reader.ReadString('\n')
fmt.Println("Message received: ", s)
}
运行:
答案 0 :(得分:2)
您的子流程正在使用\n
,但您不是在编写inwriter.WriteString("Pong\n")
inwriter.Flush()
字符,也不会刷新缓冲的编写器。
这会将预期数据写入管道:
const winston = require('winston');
const expressWinston = require('express-winston');
/**
* Custom Wiston Express Middleware to log all requests and responses in the console.
*/
module.exports = async() => {
// Creating middleware
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
const wistonMiddleware = expressWinston.logger({
transports: [
new winston.transports.Console({
json: true,
colorize: true
})
],
// optional: control whether you want to log the meta data about the request (default to true)
meta: true,
// optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
msg: 'HTTP {{req.method}} {{req.url}}',
// Use the default Express/morgan request formatting, with the same colors.
// Enabling this will override any msg and colorStatus if true. Will only output colors on transports with colorize set to true
expressFormat: true,
// Color the status code, using the Express/morgan color palette (default green, 3XX cyan, 4XX yellow, 5XX red). Will not be recognized if expressFormat is true
colorStatus: true,
ignoreRoute: function (req, res) {
return false;
} // optional: allows to skip some log messages based on request and/or response
});
return wistonMiddleware;
};