如何知道孩子是否已完成?

时间:2017-04-29 20:40:46

标签: node.js spawn

我尝试使用Node.js和socket.io通过web构建一个bash终端,我需要知道命令是否完成。有些命令比如“cdDirectory'不要发出输出,我也不知道它是否完成。如何知道命令是否完成?如果posible为每个命令设置超时? 我有以下代码:

var shell = spawn('/bin/bash');
var stdin = shell.stdin;

shell.on('exit', function() {
  socket.disconnect();
});

shell.on('close',function(){
  console.log('Close');
});

shell['stdout'].setEncoding('ascii');
shell['stdout'].on('data', function(data) {
  socket.emit('stdout', data);
});

shell['stderr'].setEncoding('ascii');
shell['stderr'].on('data', function(data) {
  socket.emit('stderr', data);
});

socket.on('stdin', function(command) {
  stdin.write(command+"\n") || socket.emit('disable');
});

stdin.on('drain', function() {
   socket.emit('enable');
});

stdin.on('error', function(exception) {
  socket.emit('error', String(exception));
});

提前致谢。

1 个答案:

答案 0 :(得分:0)

通常,spwan对象提供一个Exit事件,如here所述。我会使用spawn创建每个命令write

command.on('exit', function (code) {
  console.log('child process exited with code ' + code);
});

第二个选项是通过pidofpgrep检查您的流程是否正在运行。

相关问题