Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why's select() always blocked in non-blocking mode

Tags:

python

sockets

Although I set socket in non-blocking, seclect() function is still blocked. Please help me.

this is my code:

import socket
import select
if __name__ == '__main__':
   server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
   server.bind(("localhost",9006))
   server.listen(10)
   server.setblocking(False)
   inputs = [server]
   while True:
      try:
         a,b,c = select.select(inputs, [], [])
      except Exception:
        print ("exception")
      print ("Timeout") 
like image 637
nguyenngoc101 Avatar asked Dec 04 '22 15:12

nguyenngoc101


1 Answers

From the select docs:

The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready.

In other words, socket 'blocking' state is not relevant here. You need to specify any timeout to disable blocking; you can set 0 to make it return immediately when there is nothing to read (but note that then your loop will occupy CPU heavily).

For example:

a,b,c = select.select(inputs, [], [], 0)
like image 50
Michał Górny Avatar answered Dec 07 '22 05:12

Michał Górny