handling a job with spawn (start, termination) with socket-io Nodejs

Viewed 187

I have two questions here:

  1. is there any way to manage child_proccess (spawn) which running with nodejs?

  2. suppose I have a script that starts do some functionality, I need to start the execution with socket.io event. I need to stop this execution with another socket io event.

the first idea that came through my mind was :

start execution command with spawn and store the PID of the job in Redis. in the stop event, get PID from Redis and kill that process with another spawn with below command:

kill = spawn(`kill ${PID}`)

but os kernel does not allow nodejs to kill that process unless nodejs runs with sudo command.I am the owner of that child_procces. why I can't stop that?

the second Idea is to use global variable :

io = ()=>{
let job = null;
socket.on("start", ()=>{
    job = spawn("path/to/my/script")
})
socket.on("stop", ()=>{
   job.kill() // or procces.kill(job.pid)
})


}

so I am so confused about managing child processes with nodejs.

1 Answers

first of all you need to declare your job variable with var keyword.

when you execute the spawn command, the spawn it self generates two child process . you can use this trick for terminating the main child proccess that responsible for your job .

let PID = job.pid

kill = spawn(`kill ${PID+1}`)

this is not the desire answer but that will do your job if your child process is limited to short number

Related