Stop child process without using `kill`

I spawn a Child process via Command::new(...).spawn(). If the subprocess takes too much time, I would like to stop it. I am aware of the function kill.

I was wondering if there is a way to terminate a child more gracefully than sending SIGKILL.

SIGTERM perhaps?

send SIGTERM instead of SIGKILL

To clarify, it sems that std::process::Child does not provide a portable abstraction on top of that signal, so you may need to implement the relevant functionality for all of your target platforms using libc and the like. Or maybe there’s already a crate for that somewhere…

I would like to send something like SIGTERM using a well-designed api that is also portable to non-Linux targets.

Is this possible in the current ecosystem?

Is this possible in the current ecosystem?

I doubt it, certainly not in stdlib.It is not easy because there is no way of doing it that works reliably across platforms. See this for more details: https://superuser.com/questions/959364/on-windows-how-can-i-gracefully-ask-a-running-program-to-terminate .

If you really want to try, you can send SIGTERM on unix-like systems and write your own variant for windows using winapi directly, however quirky it might be.

You can handle SIGINT and SIGTERM in the child process. There’s ctrlc crate for this:

The child process has to cooperate. If it’s taking to much time because e.g. it’s in an infinite loop, there’s nothing you can do other than kill.

1 Like

The child has been compiled with cargo test --no-run. From what I have seen, SIGINT and SIGTERM are handeled correctly.

How do I send the correct signals on the respective platforms? Surely, I am not the first to run into these problems and other people should have found solutions to this already.