i want to build a node app which allows me to send kill -9
to all child processes of one daemon.
To be clear. We have one daemon on our server. At its start it launches a process for the communication with our clients.
When the client sends a new job to the server, a new child process is created by the daemon.
So now I want to get all child processes of the daemon, kill -9
them and then restart the daemon with systemctl restart mydaemon.service
I searched google and did not find anything that fits my issue.
What I need to say is, i want to solve this without knowing the daemons process-id, of course only if possible.
Why I need to do this is because, the software the daemon belongs to, is buggy. The communication process I mentioned above is failing and is simply gone. The seller says killing all processes is possible by just restarting the daemon, which of course is not. So because the seller can't provide any solution for our problem were currently restarting the service the same way I want to automate it now. Killing all childs with SIGKILL and then restart the daemon.
Thank you very much guys.
You can find all the child processes (recursively) using a pstree
utility. Mostly likely will need to install it. On Mac, for example, you'd do: brew install pstree
.
Then you can run this snippet to find all the child processes and kill them:
const child_process = require('child_process'); const { promisify } = require('util'); const execAsync = promisify(child_process.exec); (async () => { const pids = await execAsync( `pstree ${process.pid} | sed 's/[^0-9]*\\\\([0-9]*\\\\).*/\\\\1/' | grep -v "${process.pid}"` ); // Join the pids into one line separated by space const pidsString = pids.stdout.replace(/[\\r\\n]+/g, ' '); await execAsync(`kill -9 ${pidsString} || true`); })();
Please find the detailed explanation below:
pstree ${process.pid}
- returns a tree of all the child processes. The output looks like this:
sed 's/[^0-9]*\\\\([0-9]*\\\\).*/\\\\1/'
- keeps only the pids
, removes the rest of the strings
grep -v "${process.pid}"
- removes the current process from the list, we don't want to kill it
kill -9 ${pidsString} || true
kill -9 ${pidsString} || true
- kills the child processes with SIGKILL
.
I had to do || true
|| true
because pstree
returns a full list of processes including itself (it also spawns ps
internally). Those processes are already ended at the time when we start killing so we need it to suppress the No such process
errors.
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.