I have the following snippet starting a long-going process locally via ssh:
from asyncio import gather, run
import asyncssh
async def listen(stream):
async for line in stream:
print(line)
async def main():
async with asyncssh.connect("localhost", username="root") as conn:
process = await conn.create_process("while true; do date; sleep 1; done")
await gather(
listen(process.stdout),
listen(process.stderr),
process.wait(),
)
run(main())
Works fine for me (you have to be able to connect via ssh
locally to run the snippet, of course), except I don't know how to make sure the process gets terminated when the parent process terminates.
My first idea was to terminate()
/kill()
the process in a finally
block around gather
.
This works when the parent process got a signal it can handle, e.g SIGINT
. But in case it's been executed within an IDE/debugger or it receives SIGSEGV
the child process will stay.
Is there a way to couple the spawned process or ssh connection with the parent process in order avoid stray processes?