child_process无法识别kill()函数

时间:2017-05-16 08:54:08

标签: javascript node.js child-process kill-process

使用节点js我在MATLAB和Python中调用外部脚本 使用终端命令使用这些应用程序('start')

运行脚本效果很好

但是当我试图用kill()('stop')关闭它们时,我收到一个错误:

  

TypeError:exec.kill不是函数

我正在使用MAC OS,这是我的代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var path = require('path');

const exec = require('child_process').exec;
var cmd1 =
  '/Applications/MATLAB_R2016b.app/bin/matlab -nojvm  < /Users/dorsimon/Desktop/liftrack/Testing_Classifier.m';
var cmd2 = 'python /Users/dorsimon/Desktop/liftrack/arduino_sampling_for_workout.py';

app.get('/', function(req, res) {
  res.sendfile('index.html');
});

//Whenever someone connects this gets executed
io.on('connection', function(socket) {
  console.log('A user connected');

  fs.watch('/Users/dorsimon/Desktop/liftrack/result/', function(event, test) {
    console.log('event is: ' + event);
    fs.readFile('/Users/dorsimon/Desktop/liftrack/result/results.csv', 'utf-8', function read(
      err,
      data
    ) {
      if (err) {
        console.log('err');
        throw err;
      }
      console.log(data);
      socket.send(data);
    });
  });

  fs.watch('/Users/dorsimon/Desktop/liftrack/go', function(event, test) {
    console.log('event is: ' + event);
    fs.readFile('/Users/dorsimon/Desktop/liftrack/go/go.csv', 'utf-8', function read(err, data) {
      if (err) {
        console.log('err');
        throw err;
      }
      console.log(data);
      socket.send(data);
    });
  });

  //Whenever someone disconnects this piece of code executed
  socket.on('disconnect', function() {
    console.log('A user disconnected');
  });

  socket.on('start', function() {
    exec(cmd1, function(error, stdout, stderr) {
      // command output is in stdout
    });
    exec(cmd2, function(error, stdout, stderr) {
      // command output is in stdout
    });
  });

  socket.on('stop', function() {
    exec.kill();
  });
});

http.listen(3000, function() {
  console.log('listening on *:3000');
});

如何杀死我开始的那些child_process?

由于 DOR

1 个答案:

答案 0 :(得分:0)

您需要存储exec的返回值并在其上调用kill。为方便起见,您可以将这些值存储为socket上的属性:

socket.on('start', function() {
  socket.child1 = exec(cmd1, function(error, stdout, stderr) {
    // command output is in stdout
  });
  socket.child2 = exec(cmd2, function(error, stdout, stderr) {
    // command output is in stdout
  });
});

socket.on('stop', function() {
  socket.child1.kill();
  socket.child2.kill();
});

FWIW,您可能必须对fs.watch()的返回值执行相同操作,并在套接字关闭时调用close(),否则您的服务器可能会遇到问题已经运行了一段时间(它为每个socket.io连接创建了两个观察者,但是没有删除它们,所以它们会留下来。)