pkrumins / node-tree-kill

kill trees of processes
MIT License
333 stars 37 forks source link

Not functional on Docker Alpine #38

Open Juriy opened 2 years ago

Juriy commented 2 years ago

Hello,

Trying to use this module for killing a process tree in Docker that is built on Alpine image. Unfortunately, the module fails to create a process tree, since ps does not support some of the flags that the module is relying on: --no-headers and --ppid. This results in a process returning non-zero code. Module interprets non-zero as "no child processes" and swallows the error silently.

I was trying to find a way to change the command in buildProcessTree so that it simulates the same output. Removing header is easy - we can pass the names of the columns with -o, removing the header completely:

/usr/src/app # ps -opid=""
    1
   23
   49
   67

But lack of --ppid filter support making it slightly more challenging. My Linux knowledge is not enough to tell if manually filtering by ppid in the following command would do the trick:

/usr/src/app # ps -opid="" -oppid=""
    1     0
   23     1
   49     0
   68    49

If that's the case, it would probably be the most portable version (except for the cases when ps is not present at all as described in https://github.com/pkrumins/node-tree-kill/issues/36

If there's an ambition to rewrite this part of the code, I am happy to collaborate 🙂

m0ngr31 commented 1 year ago

@Juriy this is what I was able to whip up in my own project:

export const killChildren = (pid: number) => {
  const children = [];

  try {
    const psRes = execSync(`ps -opid="" -oppid="" |grep ${pid}`).toString().trim().split(/\n/);

    (psRes || []).forEach(pidGroup => {
      const [actual, parent] = pidGroup.trim().split(/ +/);

      if (parent.toString() === pid.toString()) {
        children.push(parseInt(actual, 10));
      }
    });
  } catch (e) {}

  try {
    kill(pid);
    children.forEach(childPid => kill(childPid));
  } catch (e) {}
};
TheThing commented 4 months ago

thanks @m0ngr31 for that code sample. I ended up stealing it and using it in my project (WTFPL). Hope you don't mind me adapting it into my library and re-licensing as such?

m0ngr31 commented 4 months ago

thanks @m0ngr31 for that code sample. I ended up stealing it and using it in my project (WTFPL). Hope you don't mind me adapting it into my library and re-licensing as such?

Go for it