from asyncio import Task, create_subprocess_exec, run, sleep
async def main():
t = Task(create_subprocess_exec('sleep', '100'))
await sleep(1)
t.cancel()
await t
run(main())
strace -t -ff -e clone,fork,vfork,execve,kill,wait4 /usr/bin/python3 test.py
22:19:20 execve("/usr/bin/python3", ["/usr/bin/python3"], 0x7ffe4ff89598 /* 50 vars */) = 0
22:19:20 vfork(strace: Process 479095 attached
<unfinished ...>
[pid 479095] 22:19:20 execve("/usr/bin/sleep", ["sleep", "100"], 0x7ffde73e6110 /* 50 vars */ <unfinished ...>
[pid 479094] 22:19:20 <... vfork resumed>) = 479095
[pid 479095] 22:19:20 <... execve resumed>) = 0
[pid 479094] 22:19:21 wait4(479095, 0x7ffde73e58d4, WNOHANG, NULL) = 0
[pid 479094] 22:19:21 wait4(479095, 0x7ffde73e5954, WNOHANG, NULL) = 0
[pid 479094] 22:19:21 kill(479095, SIGKILL) = 0
[pid 479094] 22:19:21 wait4(479095, <unfinished ...>
[pid 479095] 22:19:21 +++ killed by SIGKILL +++
22:19:21 <... wait4 resumed>[{WIFSIGNALED(s) && WTERMSIG(s) == SIGKILL}], WNOHANG, NULL) = 479095
22:19:21 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=479095, si_uid=1000, si_status=SIGKILL, si_utime=0, si_stime=0} ---
22:19:21 +++ exited with 0 +++
Documentation
It's not documented, that
.cancel()kills background process withkill(). At least on Linux:Linked PRs