当主进程突然死亡时,如何杀死 linux spawnProcess?

How do I kill linux spawnProcess when the main process suddenly dies?

我的应用程序和 spawnProcess 遇到了问题。 如果主应用程序由于某种原因 dies/is 被杀死,那么生成的进程似乎继续存在,除非我使用终端通过它们的 PID 杀死它们,否则我无法访问它们。我的目标是,如果主应用程序死了,那么生成的进程也应该以某种方式被杀死。

我的代码是这样的

auto appPid = spawnProcess("path/to/process");
scope(exit){ auto exitcode = wait(appPid); 
stderr.writeln(...);}

如果我在主进程终止时使用相同的方法,使用 wait(thisProcessID) 我会收到错误消息。 "No overload matches"。有解决这个问题的想法吗?

这里有一些代码可以在 Linux 上完成。它没有 stdlib 的 spawnProcess 的所有功能,它只是展示了最基本的功能,但如果您需要更多,从这里扩展它并不难。

import core.sys.posix.unistd;

version(linux) {
        // this function is Linux-specific
        import core.stdc.config;
        import core.sys.posix.signal;
        // we can tell the kernel to send our child process a signal
        // when the parent dies...
        extern(C) int prctl(int, c_ulong, c_ulong, c_ulong, c_ulong);
        // the constant I pulled out of the C headers
        enum PR_SET_PDEATHSIG = 1;
}

pid_t mySpawnProcess(string process) {
        if(auto pid = fork()) {
                // this branch is the parent, it can return the child pid
                // you can:
                // import core.sys.posix.sys.wait;
                // waitpid(this_ret_value, &status, 0);
                // if you want the parent to wait for the child to die
                return pid;
        } else {
                // child

                // first, tell it to terminate when the parent dies
                prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);

                // then, exec our process
                char*[2] args;
                char[255] buffer;
                // gotta copy the string into another buffer
                // so we zero terminate it and have a C style char**...
                buffer[0 .. process.length] = process[];
                buffer[process.length] = 0;
                args[0] = buffer.ptr;

                // then call exec to run the new program
                execve(args[0], args.ptr, null);
                assert(0); // never reached
        }
}

void main() {
        mySpawnProcess("/usr/bin/cat");
        // parent process sleeps for one second, then exits
        usleep(1_000_000);
}

因此需要使用较低级别的函数,但是 Linux 确实有一个函数可以满足您的需要。

当然,由于它发送了一个信号,您的 child 可能希望处理该信号以比默认终止更优雅地关闭,但是试试这个程序和 运行 ps 而它睡觉看到 cat 运行ning,然后注意到当 parent 退出时猫死了。