【问题标题】:Can't get anything from the stdout of a child process无法从子进程的标准输出中得到任何东西
【发布时间】:2014-03-08 19:18:04
【问题描述】:

我正在尝试制作一个非常简单的 nodejs 服务器,它接收 post 请求并将它们提供给一个简单的 C 程序,该程序通过 stdin 和 stdout 进行所有 I/O。我正在尝试使用以下脚本作为测试:

var prc = require('child_process').spawn('./example');

// )none of these made it work)
prc.stdout.setEncoding('ascii');
//prc.stdout.setEncoding('utf8');

prc.stdout.on('data', function (data) {
    console.log("child said something: " + data);
});

prc.stderr.on('data', function (data) {
    console.log("stderr: " + data.toString());
});

prc.on('close', function (code) {
    console.log('process exit code ' + code);
});

setInterval(function() {
    console.log("gonna write");
    prc.stdin.write("prueba inicial\n");
    console.log("wrote");
}, 2000);

example.c 包含:

int main() {
    int i;
    size_t size;
    char *line = NULL;

    for (i=0;;++i) {
        printf("\ngive me data: ");
        if (getline(&line, &size, stdin) != -1) {
            if (strcmp(line, "end\n") == 0) {
                break;
            }
            printf("result: %d, %d\n", i, i*2);
        }
    }

    return 0;
}

但我唯一能在屏幕上看到的是

gonna write
wrote
gonna write
wrote
gonna write
wrote

我知道example 正在运行,但为什么我没有通过prc.stdout 得到任何东西?

PD:使用套接字或其他东西与example 通信可能会更好,但这只是对一个真实项目的测试,我将在其中使用另一个我无法更改的 C 程序.

【问题讨论】:

标签: c node.js parent-child stdout


【解决方案1】:

需要fflush(stdout) 的原因是,因为stdio 检测到您没有在终端中运行,默认情况下它不会在'\n' 上刷新,以提高数据吞吐量。

因此您可以显式刷新,或者您只需使用更改 C 代码中的缓冲模式

setvbuf(stdout, NULL, _IOLBF, 0);

阅读this man page 了解更多信息。

【讨论】:

    【解决方案2】:

    显然,在每个printf 之后刷新stdout

    printf("result: %d, %d\n", i, i*2); 
    fflush(stdout);
    

    在看到 nodejs 脚本在 example.c 关闭时获得了所有输出后,我尝试了这一点(通过发送它end\n)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      相关资源
      最近更新 更多