AlekseyHoffman
AlekseyHoffman

Reputation: 2694

How to terminate the process created by the child process created by childProcess.exec?

Problem

As you can see from the code below, I'm executing a command on ffmpeg.exe bin using childProcess.exec() which creates 2 OS processes:

I'd like to be able to cancel the operation by terminating the ffmpeg.exe process, but neither of the following methods work, since ffmpeg.exe is a separate process:

I cannot simply terminate the returned pid with another process or run .kill() on the videoConversionProcess since it terminates the cmd.exe process, not the ffmpeg.exe process which it spawned.

Code

const command = '"E:\\test\\ffmpeg.exe" -y -i "VIDEO_URL" -vcodec copy -c copy "E:\\test\\video.ts"'
const videoConversionProcess= childProcess.exec(command)

videoConversionProcess.stdout.on('data', (data) => {
  console.log(data)     
})

When I log the videoConversionProcess I can see the information about the cmd.exe that it spawned, but not the ffmpeg.exe which is doing all the work:

ChildProcess {_events: {…}, _eventsCount: 2, _maxListeners: undefined, _closesNeeded: 3, _closesGot: 0, …}
connected: false
exitCode: null
killed: true
pid: 18804
signalCode: "SIGTERM"
spawnargs: Array(5)
0: "C:\WINDOWS\system32\cmd.exe"
1: "/d"
2: "/s"
3: "/c"
4: ""E:\test\ffmpeg.exe" -y -i "VIDEO_URL" -vcodec copy -c copy "E:\test\video.ts"
...

Question

How do I terminate the operation?

Is there a way to exec the command on the ffmpeg.exe and make Node.js aware of this process? I tried using spawn instead of exec but I couldn't make it work, it didn't spawn the ffmpeg.exe process at all.

Upvotes: 0

Views: 629

Answers (1)

Giovanni Esposito
Giovanni Esposito

Reputation: 11176

Ciao, you can try to follow this guide.

In brief, to kill a process in windows you could do:

    exec(`taskkill /PID ${pid} /T /F`, (error, stdout, stderr)=>{
        console.log("taskkill stdout: " + stdout)
        console.log("taskkill stderr: " + stderr)
        if(error){
            console.log("error: " + error.message)
        }
    })

Upvotes: 3

Related Questions