gpt4 book ai didi

c - 如何从 Node.js 发送到 stdin 并从 C 程序的 stdout 接收?

转载 作者:行者123 更新时间:2023-11-30 14:55:08 24 4
gpt4 key购买 nike

我和一位同事需要连接他的 C 程序和我的 Node.js 脚本。我试图证明使用 stdio 在两者之间传递消息的概念,但到目前为止,该概念尚未得到证明! Node 脚本在初始化时将可执行文件作为子进程启动,但随后无法发送或接收数据。

我编写了一个非常简单的 C 程序,它将在 stdin 上接收到的任何内容回显到 stdout。我不是 C 程序员,所以希望我在 16 行中没有做任何太令人震惊的事情 :p :

stream_echo.c:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFFER_SIZE 255

int main(void) {

char * buffer = calloc(BUFFER_SIZE, 1);

while(fgets(buffer, BUFFER_SIZE, stdin) != NULL) {

//Echo back on stdout:
fprintf(stdout, "echo: %s", buffer);
}
}

在控制台中进行测试表明它按预期工作: stream_echo.c running in terminal window

调用此可执行文件的node.js脚本如下:

child_stdio.js

(function() {
"use strict";

var jcp = require("child_process").spawn("./stream_echo", [], {
detached: false,
stdio: "pipe"
}),

counter = 0,

timer,

sendData = function() {
console.log("In sendData. Connected: " + jcp.connected);

counter += 1;
jcp.stdin.write("This is data " + counter + "\r\n");

timer = setTimeout(sendData, 2000);
};


//******** STDIN ********
jcp.stdin.on("close", (data) => {
console.log("stdin closed.");
if (timer) {
clearTimeout(timer);
}
});


//******** STDOUT ********
jcp.stdout.on("data", (data) => {
console.log("stdout: " + data);
});

jcp.stdout.on("close", (data) => {
console.log("stdout closed.");
});


//******** STDERR ********
jcp.stderr.on("data", (data) => {
console.log("stderr: " + data);
});

jcp.stderr.on("close", (data) => {
console.log("stderr closed.");
});


//******** PROCESS ********
jcp.on("close", (code, signal) => {
console.log("Child process closed.\nCode: " + code + "\nSignal: " + signal);
});

jcp.on("exit", (code, signal) => {
console.log("Child process exited.\nCode: " + code + "\nSignal: " + signal);
});

jcp.on("disconnect", () => {
console.log("Child process disconnected.");
});

console.log("jcp.pid: " + jcp.pid);
console.log("Connected: " + jcp.connected);
console.log("Calling sendData for the first time....");
sendData();

}());

当我运行此脚本时,多次尝试将数据发送到子进程,并且没有报告任何错误(尽管进程的 connected 属性为 false),但也没有收到任何消息。当我终止子进程时,会触发流关闭事件和进程关闭事件,并且脚本正常终止。

Execution of child_stdio.js

我不明白为什么 connected 为 false 但关闭事件会触发。我觉得这是一个重要线索。

谁能告诉我在互联网上拖网几个小时不能做到什么?

最佳答案

stdout未连接到终端时,它是 block 缓冲的。这意味着在缓冲区填满或应用程序终止之前,输出不会被刷新。

在 C 应用程序中的 fprintf 之后添加 fflush(stdout)

关于c - 如何从 Node.js 发送到 stdin 并从 C 程序的 stdout 接收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46195785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com