简体   繁体   English

无法杀死 Ubuntu 上的 ChildProcess

[英]Cannot kill ChildProcess on Ubuntu

I am trying to kill the application in Ubuntu.我试图杀死 Ubuntu 中的应用程序。 I have the following code:我有以下代码:

import {ChildProcess, exec} from "child_process";

export default class VisiviTTS {
    private static process?: ChildProcess;

    public static speak(text: string): void {
        this.process = exec(`espeak -v czech "${text}"`);
    }

    public static stop() {
        this.process?.kill("SIGINT");
    }
}

On ArchLinux, everything works.在 ArchLinux 上,一切正常。 On Ubuntu, it does not kill the process.在 Ubuntu 上,它不会终止进程。 I have tried SIGTERM , SIGKILL , destroying stderr and stdout , emitting exit and kill on it, but without any success.我试过SIGTERMSIGKILL ,破坏stderrstdout ,发出exitkill ,但没有任何成功。

When executing something via NodeJS's exec() , it returns the ChildProcess of /bin/sh , where is executed my script.通过 NodeJS 的exec()执行某些操作时,它返回/bin/sh的 ChildProcess ,我的脚本在哪里执行。

Ubuntu does not act like ArchLinux, and if I kill the parent process, child processes will be still alive and probably orphaned. Ubuntu 不像 ArchLinux,如果我杀死父进程,子进程将仍然存在并且可能是孤立的。 Thus my script is still alive.因此,我的脚本仍然存在。

So I wrote a recursive function, which kills all children of the process.所以我写了一个递归的 function,它杀死了进程的所有子进程。

import {ChildProcess, exec} from "child_process";
import {EOL} from "os";

export default class VisiviTTS {
    private static process?: ChildProcess;

    public static speak(text: string): void {
        this.process = exec(`espeak -v czech "${text}"`);
    }

    public static stop() {
        if(this.process?.kill("SIGINT"))
            this.kill(this.process?.pid);
    }

    static kill(pid?: number) {
        console.log(pid);
        exec(`ps -o pid= --ppid ${pid}`, (err, stdout) => {
            console.log(err);

            stdout.split(EOL).forEach((line: string) => {
                const num = Number(line);
                if (num > 0) {
                    this.kill(num);

                    console.log(`Killing process ${num}`);
                    exec(`kill -9 ${num}`)
                }
            });
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM