我希望在Linux上使用top和child_process.exec连续地从监控进程和系统资源使用中获取数据。
代码:
const { exec } = require('child_process');
exec('top', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log('stdout', stdout);
console.log('stderr', stderr);
});如果我在上面运行代码,就会得到一个错误exec error: Error: stdout maxBuffer exceeded。
我使用的是Node.js版本v8.9.4
可以使用top命令连续地使用child_process.exec获取数据。
发布于 2018-08-22 13:47:42
您不能使用exec,因为top永远不会结束。改用spawn,并将top切换到batch mode
const { spawn } = require('child_process');
const top = spawn('top', ['-b']);
top.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
top.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
top.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});发布于 2018-08-22 14:23:10
exec()将缓冲stdout。
生成一个shell,然后在该shell中执行命令,缓冲任何生成的输出。
(从医生那里。)
当top在没有进一步参数的情况下启动时,它尝试重新绘制终端的部分内容。我不知道你竟然走了这么远。在我的系统中,您的代码失败了:
顶部:失败的tty
您需要告诉top在批处理模式下运行,以便它将在每次更新时完全转储其当前状态。
exec('/usr/bin/top -b', ...);尽管由于top将无限期地转储状态,缓冲区最终仍然会溢出。可以使用-n #开关或使用spawn()限制更新的次数。
const { spawn } = require("child_process");
// Note: -b for batch mode and -n # for number of updates
let child = spawn("/usr/bin/top", ["-b", "-n", "2"]);
// Listen for outputs
child.stdout.on("data", (data) => {
console.log(`${data}`);
});使用子进程stdout流上的stdout侦听器,您可以及时观察数据。
https://stackoverflow.com/questions/51967909
复制相似问题