简体   繁体   中英

How to kill child_process in node.js — req.on close

I am trying to kill the child process when "requst.on('close' " is called. But child.pid inside this callback always points to most recent request. The question is: how can I match the child.pid to the request? Thanks

var query_script = "query.py"
var express = require('express');
var app = express();
var spawn = require('child_process').spawn;

app.get('/:version/query', function(request, response) {
    child = spawn('python, ['query.py', request.originalUrl])
    console.log("start pid=" + child.pid + ": " + request.originalUrl)

    request.on('close', function () {
        console.log("1: current pid=" + child.pid)    
        //child.kill('SIGTERM');
    })

    child.stdout.pipe(response)
});

app.listen(3000);
console.log('Listening on port 3000...');

通过将var放在闭包中来定义child

var child = spawn('python, ['query.py', request.originalUrl])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM