【问题标题】:How to know if a child procces is finished?如何知道子进程是否完成?
【发布时间】:2017-04-29 20:40:45
【问题描述】:

我尝试使用 Node.js 和 socket.io 通过 web 构建一个 bash 终端,我需要知道命令是否完成。像“cd someDirectory”这样的命令不会发出输出,我不知道它是否完成。如何知道命令是否完成?如果可以为每个命令设置超时? 我有以下代码:

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));
});

提前致谢。

【问题讨论】:

    标签: node.js spawn


    【解决方案1】:

    一般来说,spwan 对象提供了一个退出事件,如here 所述。我会将每个命令创建为spawn,而不是使用write

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      相关资源
      最近更新 更多