Home > Back-end >  Kill process.exec function
Kill process.exec function

Time:01-12

I have a function to execute a process:

static async runTest() { await process.exec(`start ${currentDir}/forward.py`); }

runTest();

The python script will continue to run until it's killed, which I don't know how to do at the moment. So in short, I want to kill this process manually at some point. How I would I do this? Thank you!

CodePudding user response:

The exec return value is a child-process object and you can kill it anytime by calling the .kill() function. For more info, you can refer to this

https://nodejs.org/api/child_process.html

I demonstrated the kill function using a simple timeout.

const { exec } = require('child_process');
    
    let childprocess = exec('python a.py', (error, stdout, stderr) => {
        if (error) {
            console.error(`error: ${error.message}`);
            return;
        }
    
        if (stderr) {
            console.error(`stderr: ${stderr}`);
            return;
        }
    
        console.log(`stdout:\n${stdout}`);
    });
    
    setTimeout(() => {  //Example killing
        childprocess.kill() 
    }, 2000);
  •  Tags:  
  • Related