Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing a bash script does not kill child processes

I have written a test script which runs another script to start the server to test. When the tests have completed a SIGKILL message is sent to the server process, however when running the test script again the server throws a EADDRINUSE error (I‘m in a node.js environment) which means the port the server is trying to mount to is currently in use. The process we tried to kill with a SIGKILL is still running. I don‘t believe this is a node specific issue, but rather a lack of education on my end for how bash processes work.

Here are some specifics, this is my start script called scripts/start-node.sh:

#!/bin/bash

node_modules/.bin/babel-node --stage 0 index.js

This is my node server called index.js (I haven‘t authored any process event listeners):

Http.createServer(…).listen(PORT, () => console.log(`Server listening on ${PORT}`))

And the start script is controlled with the node child_process module:

var child = child_process.spawn('scripts/start-node.sh')
// Later…
child.kill('SIGKILL')
like image 791
Calebmer Avatar asked Oct 25 '15 01:10

Calebmer


People also ask

Does kill kill child processes?

Killing a parent doesn't kill the child processes Every process has a parent. We can observe this with pstree or the ps utility. The ps command displays the PID (id of the process), and the PPID (parent ID of the process).

How can we stop child processes?

For killing a child process after a given timeout, we can use the timeout command. It runs the command passed to it and kills it with the SIGTERM signal after the given timeout. In case we want to send a different signal like SIGINT to the process, we can use the –signal flag.

What happens to child process when parent is killed Linux?

When a parent process dies before a child process, the kernel knows that it's not going to get a wait call, so instead it makes these processes "orphans" and puts them under the care of init (remember mother of all processes).

Can we kill bash process?

You can use the command pkill to kill processes. If you want to "play around", you can use "pgrep", which works exactly the same but returns the process rather than killing it. Save this answer.


1 Answers

Simply:

#!/bin/bash
if pgrep -x "node" > /dev/null
then
mv -f  /usr/local/bin/node /usr/local/bin/node.1
killall  node
mv -f /usr/local/bin/node.1 /usr/local/bin/node
which node
else
echo "process node not exists"
fi

node is creating child process every-time we kill it. So it's not possible to kill the process from kill,pkill or killall commands. So we are removing node command to make forking process fail and then we kill the process.Finally we restore the node command.

like image 130
Akhil Avatar answered Sep 29 '22 12:09

Akhil