why do i get a bad file descriptor error?

徘徊边缘 提交于 2019-12-10 15:17:35

问题


i got an error for bad file descriptor for this code for the udp server program i made

from socket import *

s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 890))

while True:
   (c,a) = s.recvfrom(1024)
   msg = 'thanks for requesting'
   s.sendto(msg,a)
   s.close()

the error message i got was

Traceback (most recent call last):
File "udpserv.py", line 7, in <module>
(c,a) = s.recvfrom(1024)
 File "/usr/lib/python2.7/socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor

can anyone please tell me how i got this error and how to solve it?


回答1:


You get this error because you close the socket and then call recvfrom again.

If you add a print after the line with recvfrom, you'll notice that the first call to recvfrom works as expected. The second call (after looping once) throws the error you see.

Fix your code by simply removing s.close(). (You don't need to close the connection to the client as UDP doesn't have that concept, in contrast to TCP if you had that in mind.)




回答2:


You can get that same error if you have an infinite while loop. In my case I replaced the

while True:

with

count = 0
while (count < 10):
    count += 1
    #rest of the code


来源:https://stackoverflow.com/questions/36966374/why-do-i-get-a-bad-file-descriptor-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!