在Node.js中,怎么向spawn和exec产生的子进程的stdin输入东西?? - CNode技术社区

在Node.js中,怎么向spawn和exec产生的子进程的stdin输入东西??
发布于 12 年前 作者 friskit-china 20470 次浏览 最后一次编辑是 9 年前

例如程序:

#include <stdio.h>
int main(){
 int a,b;
 while(scanf("%d %d", &a, &b)!=EOF)
 printf("%d\n",a+b);
 return 0;
}

然后通过

var exec = require('child_process').exec;
var childProcess = exec('a.out',
 function(err, stdout, stderr){
 //balabalabala
 //我想向a.out的stdio中输入东西需要怎么做啊......
 }
);
5 回复

这样试试:

var spawn = require('child_process').spawn;
var proc = spawn('./a.out');
proc.stdout.pipe(process.stdout); // 把子进程的输出导向控制台
proc.stdin.write('2 4\n6 8\n'); // 写入数据
proc.stdin.end(); 

执行后,在控制台观察输出。

采用child_process的exec方法可以这样来写:

var exec = require('child_process').exec;
var child = exec('./a.out', function (err, stdout, stderr) {
 console.log(stdout); // 直接查看输出
});
child.stdin.write('2 4\n6 8\n'); // 输入
child.stdin.end(); 
var exec = require('child_process').exec;
var ch = exec('./a.out');
process.stdin.pipe(ch.stdin); // 将父进程的stdin输入到子进程(c program)中
ch.stdout.pipe(process.stdout); // 将子进程的输出(stdout)输出到父进程的stdout中
ch.stderr.pipe(process.stdout); // 与上一个类似 不过是stderr

可以试着把最后两行pipe函数去掉,看看有什么结果 :)

exec也有stdin这些数据成员??这个主要是我疑惑的地方......

感觉就是通过重定向,把子进程包在了父进程中......等手边有环境了试试哈~多谢~

@friskit-china 别疑惑了。官网文档http://nodejs.org/api/child_process.html,

  • child_process.spawn(command, [args], [options])
  • child_process.exec(command, [options], callback)
  • child_process.execFile(file, [args], [options], [callback])
  • child_process.fork(modulePath, [args], [options])

这4个函数都返回ChildProcess对象。 Class ChildProcess也在那个网页上有介绍。

回到顶部

AltStyle によって変換されたページ (->オリジナル) /