python / cpython

The Python programming language
https://www.python.org/
Other
61.27k stars 29.55k forks source link

asyncio.create_subprocess() cancellation #118516

Open socketpair opened 2 months ago

socketpair commented 2 months ago

Documentation

It's not documented, that .cancel() kills background process with kill(). At least on Linux:

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 +++
socketpair commented 2 months ago

I think here: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_exec and here: https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.create_subprocess_exec