消除 child 过程数据的缓冲
Eliminate buffering of a child process data
我尝试从 node.js 脚本 (parent) 创建一个 child 进程,这样 parent 和 child 之间不会有任何干扰] 数据流。当 child 进程启动并能够终止它时,parent 应该只有 child 进程 ID。 child_process.exec
完成了我需要的一部分,但不幸的是它缓冲了 child 的输出,因此当缓冲区满时 child 崩溃。有没有办法消除缓冲? child 过程本质上是无限的(数据流)。或者可能有其他方法来实施控制?
代码示例(仅供演示):
const { exec } = require('child_process');
const keypress = require('keypress');
keypress(process.stdin);
var c1;
process.stdin.on('keypress', (letter, key) => {
if (key && key.name == 'a') {
c1.kill();
} else if (key && key.name == 'b') {
c1 = exec('ffplay -i udp://localhost:4000', (err, stdout, stderr) => {
if (err) {
console.error(`error: ${err}`);
}
});
}
});
我试过了spawn
但是child - parent干扰更严重
如果您改用 child_process.spawn
,您应该可以使用 stdio
:
的选项来调用它
spawn(cmd, [], { stdio: 'ignore' });
编辑:
如果您是 Promise
的粉丝,这是我写的一个 util fn 来帮助解决问题
const quietSpawn = (cmd, args = []) => {
const splitCmd = cmd.split(' ');
if (splitCmd.length > 1) {
[cmd, ...args] = splitCmd;
}
return new Promise((resolve, reject) => {
const proc = spawn(cmd, args, { stdio: 'ignore' });
proc.on('exit', resolve);
proc.on('error', reject);
});
};
我尝试从 node.js 脚本 (parent) 创建一个 child 进程,这样 parent 和 child 之间不会有任何干扰] 数据流。当 child 进程启动并能够终止它时,parent 应该只有 child 进程 ID。 child_process.exec
完成了我需要的一部分,但不幸的是它缓冲了 child 的输出,因此当缓冲区满时 child 崩溃。有没有办法消除缓冲? child 过程本质上是无限的(数据流)。或者可能有其他方法来实施控制?
代码示例(仅供演示):
const { exec } = require('child_process');
const keypress = require('keypress');
keypress(process.stdin);
var c1;
process.stdin.on('keypress', (letter, key) => {
if (key && key.name == 'a') {
c1.kill();
} else if (key && key.name == 'b') {
c1 = exec('ffplay -i udp://localhost:4000', (err, stdout, stderr) => {
if (err) {
console.error(`error: ${err}`);
}
});
}
});
我试过了spawn
但是child - parent干扰更严重
如果您改用 child_process.spawn
,您应该可以使用 stdio
:
spawn(cmd, [], { stdio: 'ignore' });
编辑:
如果您是 Promise
的粉丝,这是我写的一个 util fn 来帮助解决问题
const quietSpawn = (cmd, args = []) => {
const splitCmd = cmd.split(' ');
if (splitCmd.length > 1) {
[cmd, ...args] = splitCmd;
}
return new Promise((resolve, reject) => {
const proc = spawn(cmd, args, { stdio: 'ignore' });
proc.on('exit', resolve);
proc.on('error', reject);
});
};