@@ -328,13 +328,13 @@ async def _sock_sendfile_native(self, sock, file, offset, count):
328
328
return 0 # empty file
329
329
330
330
fut = self .create_future ()
331
- fd = sock .fileno ()
332
- self ._sock_sendfile_native_impl (fut , None , fd , fileno ,
331
+ self ._sock_sendfile_native_impl (fut , None , sock , fileno ,
333
332
offset , count , blocksize , 0 )
334
333
return await fut
335
334
336
- def _sock_sendfile_native_impl (self , fut , registered_fd , fd , fileno ,
335
+ def _sock_sendfile_native_impl (self , fut , registered_fd , sock , fileno ,
337
336
offset , count , blocksize , total_sent ):
337
+ fd = sock .fileno ()
338
338
if registered_fd is not None :
339
339
# Remove the callback early. It should be rare that the
340
340
# selector says the fd is ready but the call still returns
@@ -354,8 +354,11 @@ def _sock_sendfile_native_impl(self, fut, registered_fd, fd, fileno,
354
354
try :
355
355
sent = os .sendfile (fd , fileno , offset , blocksize )
356
356
except (BlockingIOError , InterruptedError ):
357
- self .add_writer (fd , self ._sock_sendfile_native_impl , fut , fd , fd ,
358
- fileno , offset , count , blocksize . total_sent )
357
+ if registered_fd is None :
358
+ self ._sock_add_cancellation_callback (fut , sock )
359
+ self .add_writer (fd , self ._sock_sendfile_native_impl , fut ,
360
+ fd , sock , fileno ,
361
+ offset , count , blocksize . total_sent )
359
362
except OSError as exc :
360
363
if total_sent == 0 :
361
364
# We can get here for different reasons, the main
@@ -380,14 +383,24 @@ def _sock_sendfile_native_impl(self, fut, registered_fd, fd, fileno,
380
383
else :
381
384
offset += sent
382
385
total_sent += sent
386
+ if registered_fd is None :
387
+ self ._sock_add_cancellation_callback (fut , sock )
383
388
self .add_writer (fd , self ._sock_sendfile_native_impl , fut ,
384
- fd , fd , fileno ,
389
+ fd , sock , fileno ,
385
390
offset , count , blocksize , total_sent )
386
391
387
392
def _sock_sendfile_update_filepos (self , fileno , offset , total_sent ):
388
393
if total_sent > 0 :
389
394
os .lseek (fileno , offset , os .SEEK_SET )
390
395
396
+ def _sock_add_cancellation_callback (self , fut , sock ):
397
+ def cb (fut ):
398
+ if fut .cancelled ():
399
+ fd = sock .fileno ()
400
+ if fd != - 1 :
401
+ self .remove_writer (fd )
402
+ fut .add_done_callback (cb )
403
+
391
404
392
405
class _UnixReadPipeTransport (transports .ReadTransport ):
393
406
0 commit comments