Ошибка recv errno 11

I want to make a program that accesses images from files, encodes them, and sends them to an server.
Than the server is supposed to decode the image, and save it to file.
I tested the image encoding itself, and it worked, so the problem lies in the server and client connection.

Here is the server:

import socket
import errno
import base64

from PIL import Image
import StringIO

def connect(c):
    try:
        image = c.recv(8192)
        return image
    except IOError as e:
        if e.errno == errno.EWOULDBLOCK:
            connect(c)


def Main():
    host = '138.106.180.21'
    port = 12345

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    s.bind((host, port))
    s.listen(1)


    while True:

        c, addr = s.accept()
        c.setblocking(0)

        print "Connection from: " + str(addr)

        image = c.recv(8192)#connect(c)

        imgname = 'test.png'

        fh = open(imgname, "wb")
        if image == 'cusdom_image':
            with open('images.png', "rb") as imageFile:
                image = ''
                image = base64.b64encode(imageFile.read())
                print image
        fh.write(image.decode('base64'))
        fh.close()


if __name__ == '__main__':
    Main()

And here is the client:

import socket
import base64

from PIL import Image
import StringIO
import os, sys

ip = '138.106.180.21'
port = 12345
print 'Add event executed'
s = socket.socket()
s.connect((ip, port))

image_path = '/home/gilgamesch/Bilder/Bildschirmfoto.png'

print os.getcwd()
olddir = os.getcwd()
os.chdir('/')
print os.getcwd()

if image_path != '':
    with open(image_path, "rb") as imageFile:
        image_data = base64.b64encode(imageFile.read())
        print 'open worked'
else:
    image_data = 'cusdom_image'

os.chdir(olddir)

s.send(image_data)


s.close()

And the error message is:

Traceback (most recent call last):
  File "imgserv.py", line 49, in <module>
    Main()
  File "imgserv.py", line 34, in Main
    image = c.recv(8192)#connect(c)
socket.error: [Errno 11] Resource temporarily unavailable

On Nexus devices, my streaming app sometimes stops with:

09-08 11:01:34.640: ERROR/HTTPStream(34): recv failed, errno = 11 (Try
again)
09-08 11:13:45.130: ERROR/HTTPStream(34): recv failed, server
is gone, total received: 12272 bytes

The first error is more common.
This does not happen on G1 devices.

My code looks like this:

mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);

new Thread(new Runnable() {
    public void run() {
        try {
            mediaPlayer.setDataSource(getString(R.string.URL));
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace(e);
        }
    }
}).start();   

Why does this error occur on Nexus devices?

(in continuation to bug https://bugs.python.org/issue25471 )

socket.recv() raises ‘BlockingIOError: [Errno 11] Resource temporarily unavailable’ in case, if setblocking(False) on socket returned by non-blocking socket’s .accept() method and client does not sending data and didn’t disconnected yet.

Not sure if I’m correct, but reading glibc doc on recv(), I think raised exception should be corrected: while code 11 correctly corresponds to EWOULDBLOCK, the misleading description ‘Resource temporarily unavailable’, probably, should be changed:

‘EWOULDBLOCK’
Nonblocking mode has been set on the socket, and the read
operation would block. (Normally, ‘recv’ blocks until there
is input available to be read.)

attached file with testing server corrected for this issue

I am using c sockets to implement a reliable UDP protocol. I am using the following code to set a timeout on a socket in which I’m waiting for an acknowledgement. I am not sure why I am getting errno 11, resource temporarily unavailable.

        //set timer for recv_socket
        struct timeval tv;
        tv.tv_usec = TIMEOUT_MS;

        if(setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0){
            printf("Error setting the socket timeout.n");
        }

        int recv_msg_len;
        if(recv_msg_len = recvfrom(rcv_sock, ackBuffer,sizeof(ackBuffer), 0,
               (struct sockaddr *) &servAddr2, &fromSize) < 0){
            //timeout reached
            printf("Error Reporting: %d : %sn", errno, strerror(errno));
            num_timeouts++;
        }

I have also tried the select method that was mentioned in the comments. I have the following code inside a loop, but the recvfrom never times out.

        fd_set set;
        FD_ZERO(&set);      /* empties the set */
        FD_CLR(rcv_sock,&set);    /* removes FD from the set */
        FD_SET(rcv_sock,&set);    /* adds FD to the set */

        if(select(rcv_sock + 1, &set, NULL, NULL, &tv) < 0){
            printf("nError Reporting: %d : %snn", errno, strerror(errno));
            return -1;
        }


        if(!FD_ISSET(rcv_sock,&set)){   /* true if FD is in the set */
            printf("socket is not set properly.n");
        }

I want to make a program that accesses images from files, encodes them, and sends them to an server.
Than the server is supposed to decode the image, and save it to file.
I tested the image encoding itself, and it worked, so the problem lies in the server and client connection.

Here is the server:

import socket
import errno
import base64

from PIL import Image
import StringIO

def connect(c):
    try:
        image = c.recv(8192)
        return image
    except IOError as e:
        if e.errno == errno.EWOULDBLOCK:
            connect(c)


def Main():
    host = '138.106.180.21'
    port = 12345

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    s.bind((host, port))
    s.listen(1)


    while True:

        c, addr = s.accept()
        c.setblocking(0)

        print "Connection from: " + str(addr)

        image = c.recv(8192)#connect(c)

        imgname = 'test.png'

        fh = open(imgname, "wb")
        if image == 'cusdom_image':
            with open('images.png', "rb") as imageFile:
                image = ''
                image = base64.b64encode(imageFile.read())
                print image
        fh.write(image.decode('base64'))
        fh.close()


if __name__ == '__main__':
    Main()

And here is the client:

import socket
import base64

from PIL import Image
import StringIO
import os, sys

ip = '138.106.180.21'
port = 12345
print 'Add event executed'
s = socket.socket()
s.connect((ip, port))

image_path = '/home/gilgamesch/Bilder/Bildschirmfoto.png'

print os.getcwd()
olddir = os.getcwd()
os.chdir('/')
print os.getcwd()

if image_path != '':
    with open(image_path, "rb") as imageFile:
        image_data = base64.b64encode(imageFile.read())
        print 'open worked'
else:
    image_data = 'cusdom_image'

os.chdir(olddir)

s.send(image_data)


s.close()

And the error message is:

Traceback (most recent call last):
  File "imgserv.py", line 49, in <module>
    Main()
  File "imgserv.py", line 34, in Main
    image = c.recv(8192)#connect(c)
socket.error: [Errno 11] Resource temporarily unavailable

Я хочу сделать программу, которая обращается к изображениям из файлов, кодирует их и отправляет их на сервер. Чем сервер должен декодировать изображение и сохранить его в файл. Я сам тестировал кодировку изображений, и она работала, поэтому проблема заключается в подключении к серверу и клиенту.

Вот сервер:

import socket
import errno
import base64

from PIL import Image
import StringIO

def connect(c):
    try:
        image = c.recv(8192)
        return image
    except IOError as e:
        if e.errno == errno.EWOULDBLOCK:
            connect(c)


def Main():
    host = '138.106.180.21'
    port = 12345

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    s.bind((host, port))
    s.listen(1)


    while True:

        c, addr = s.accept()
        c.setblocking(0)

        print "Connection from: " + str(addr)

        image = c.recv(8192)#connect(c)

        imgname = 'test.png'

        fh = open(imgname, "wb")
        if image == 'cusdom_image':
            with open('images.png', "rb") as imageFile:
                image = ''
                image = base64.b64encode(imageFile.read())
                print image
        fh.write(image.decode('base64'))
        fh.close()


if __name__ == '__main__':
    Main()

И вот клиент:

import socket
import base64

from PIL import Image
import StringIO
import os, sys

ip = '138.106.180.21'
port = 12345
print 'Add event executed'
s = socket.socket()
s.connect((ip, port))

image_path = '/home/gilgamesch/Bilder/Bildschirmfoto.png'

print os.getcwd()
olddir = os.getcwd()
os.chdir('/')
print os.getcwd()

if image_path != '':
    with open(image_path, "rb") as imageFile:
        image_data = base64.b64encode(imageFile.read())
        print 'open worked'
else:
    image_data = 'cusdom_image'

os.chdir(olddir)

s.send(image_data)


s.close()

И сообщение об ошибке:

Traceback (most recent call last):
  File "imgserv.py", line 49, in <module>
    Main()
  File "imgserv.py", line 34, in Main
    image = c.recv(8192)#connect(c)
socket.error: [Errno 11] Resource temporarily unavailable

Доброго времени, суток.

Обнаружил вот какую проблему.

Если я сейчас выну сетевой кабель из сетевой карты, то, хотя никакой сети уже не будет, все приложения, которые используют постоянное подключение, будут считать, что сеть работает. К примеру, jabber клиенты остаются подключенными к серверу, и когда я пытаюсь отослать кому-нибудь сообщение, никаких ошибок не возникает, и всё указывает на то, что сообщение отправлено, хотя, естественно, оно никак не может быть отправлено.

Если же вставить кабель обратно, то ничего не изменится — сеть работать все равно не будет, а приложения будут думать, что она работает.

Пробовал запускать /etc/init.d/networking restart и заново поднимать VPN соединение — сеть начинает работать, но те приложения, которые используют постоянное подключение, до сих пор не работают. А именно, они считают, что все нормально работает, а на самом не отсылают в сеть и байта информации. В случае jabber клиента это исправляется путем ухода в offline, а потом обратно в online (т. е. как раз этими действиями я закрываю постоянное TCP соединение и открываю новое).

В данном примере я сам выдергиваю сетевой кабель, но если неполадки в сети случились не по моей вине, то я никак не замечаю, что сеть не работает, и отправляю сообщения через jabber, которые не доходят до получателя, не подозревая об этом.

Данная проблема наблюдается как при работе в интернет по VPN соединению, так и в локальной сети.

Подскажите, пожалуйста, в какую сторону копать. Совершенно невозможно работать с IM клиентами — нет никакой гарантии, что сообщение дошло до получателя. :( Буду очень благодарен за помощь.

Информация, которая на мой взгляд может помочь в решении проблемы:
Ubuntu 7.04 (обновлялся с 6.10), eth0 — сеть между двумя компьютерами дома, через нее по NAT’у второй компьютер выходит в интернет, eth1 — локальная городская сеть, ppp0 — VPN подключение, соединяющее меня с интернетом.
Ниже приведен вывод команды ifconfig до вынимания сетевого кабеля и после.

До:

Код:

eth0 Link encap:Ethernet HWaddr 00:0F:EA:2E:E5:8F
inet addr:192.168.0.1 Bcast:192.168.0.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:19 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 b) TX bytes:3703 (3.6 KiB)
Interrupt:19 Base address:0x4000

eth1 Link encap:Ethernet HWaddr 00:50:FC:F5:C6:DD
inet addr:10.100.43.13 Bcast:10.100.43.255 Mask:255.255.255.0
inet6 addr: fe80::250:fcff:fef5:c6dd/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:39898 errors:0 dropped:0 overruns:0 frame:0
TX packets:62556 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3288355 (3.1 MiB) TX bytes:77257457 (73.6 MiB)
Interrupt:21 Base address:0x4000

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:20 errors:0 dropped:0 overruns:0 frame:0
TX packets:20 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1204 (1.1 KiB) TX bytes:1204 (1.1 KiB)

ppp0 Link encap:Point-to-Point Protocol
inet addr:192.168.85.222 P-t-P:172.16.16.1 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1
RX packets:9920 errors:0 dropped:0 overruns:0 frame:0
TX packets:14299 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:3
RX bytes:669641 (653.9 KiB) TX bytes:9848957 (9.3 MiB)

После:

Код:

eth0 Link encap:Ethernet HWaddr 00:0F:EA:2E:E5:8F
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:35 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 b) TX bytes:5660 (5.5 KiB)
Interrupt:16 Base address:0xe000

eth1 Link encap:Ethernet HWaddr 00:50:FC:F5:C6:DD
inet6 addr: fe80::250:fcff:fef5:c6dd/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4449 errors:0 dropped:0 overruns:0 frame:0
TX packets:5021 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:515277 (503.2 KiB) TX bytes:2812167 (2.6 MiB)
Interrupt:21 Base address:0x6000

eth0:avah Link encap:Ethernet HWaddr 00:0F:EA:2E:E5:8F
inet addr:169.254.8.205 Bcast:169.254.255.255 Mask:255.255.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Interrupt:16 Base address:0xe000

eth1:avah Link encap:Ethernet HWaddr 00:50:FC:F5:C6:DD
inet addr:169.254.12.145 Bcast:169.254.255.255 Mask:255.255.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Interrupt:21 Base address:0x6000

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:20 errors:0 dropped:0 overruns:0 frame:0
TX packets:20 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1204 (1.1 KiB) TX bytes:1204 (1.1 KiB)

my system: ubuntu16.04; PyCharm; python2.7.12; virtualenv;
when test sctp connect, this error occurred to me:

Traceback (most recent call last):
File "/home/test/Downloads/pycharm-community-2017.1.1/helpers/pydev/pydevd.py", line 1578, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/home/test/Downloads/pycharm-community-2017.1.1/helpers/pydev/pydevd.py", line 1015, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/home/test/PycharmProjects/sctp_socket/server.py", line 215, in <module>
someone access:  ('127.0.0.1', 50750)
    fromaddr, flags, msg, notif = conn_sock.sctp_recv(BUFSIZE)
  File "/home/test/sctp_env/local/lib/python2.7/site-packages/sctp.py", line 1206, in sctp_recv
    (fromaddr, flags, msg, _notif) = _sctp.sctp_recv_msg(self._sk.fileno(), maxlen)
IOError: [Errno 11] Resource temporarily unavailable

but it’s OK in terminal:

(sctp_env) test@ubuntu:~/PycharmProjects/sctp_socket$ python server.py

my server code:

import sctp

HOST = ''
PORT = 3868
BUFSIZE = 2048
ADDR = (HOST, PORT)

socket_serv = sctp.sctpsocket_tcp(socket.AF_INET)  # , sctp.IPPROTO_SCTP

socket_serv.initparams.max_instreams = 3
socket_serv.initparams.num_ostreams = 3

socket_serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket_serv.bindx([ADDR])
socket_serv.listen(5)
socket_serv.setblocking(1)
socket_serv.events.data_io = 1
socket_serv.events.clear()

while True:
    conn_sock, addr = socket_serv.accept()
    print 'someone access:  ', addr
    msg = ''
    while True:
        fromaddr, flags, msg, notif = conn_sock.sctp_recv(BUFSIZE)
        if not msg:
            print 'msg == 0!!'
            break
        print 'recv: %s' % msg
        
    conn_sock.close()
socket_serv.close()

client.py:

import sctp
from sctp import *

server = "localhost"
tcpport = 3868

if _sctp.getconstant("IPPROTO_SCTP") != 132:
    raise "getconstant failed"
client_sock = sctpsocket(socket.AF_INET, socket.SOCK_STREAM, None)
saddr = (server, tcpport)
client_sock.initparams.max_instreams = 3
client_sock.initparams.num_ostreams = 3
client_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client_sock.setblocking(0)
client_sock.events.clear()
client_sock.events.data_io = 1
client_sock.connect(saddr)

while 1:
    while True:
        data = raw_input('INPUT: ')
        if not data:
            break
        client_sock.sctp_send(data)
        fromaddr, flags, msg, notif = client_sock.sctp_recv(1024)
        print "%s____" % msg
    break
client_sock.close()

Error occurred in line: fromaddr, flags, msg, notif = conn_sock.sctp_recv(BUFSIZE)
please tell me why does this Error come out…THX


0

0

При чтении из СОМ порта read() возрщает ошибку, errno=11 Что это значит?

что значит errno=11 ? В каком мануале расписаны коды ошибок?

  • Ссылка

EAGAIN устройство не готово к выводу. Видимо еще данных нет.

  • Показать ответ
  • Ссылка

Re: Чтение СОМ порта… errno=11

в каком *.h файле расписаный коды ошибок?

binr ★★

(26.02.06 14:29:25 MSK)

  • Показать ответ
  • Ссылка

Re: Чтение СОМ порта… errno=11

к коду 11 соответсвует коментарий try again, что бы это значило по отношению к драйверу СОМ порта? Почему я такого не встречал в qnx?

binr ★★

(26.02.06 14:36:39 MSK)

  • Ссылка

Re: Чтение СОМ порта… errno=11

Да, видимо нет данных…

binr ★★

(26.02.06 14:38:39 MSK)

  • Ссылка

Re: Чтение СОМ порта… errno=11

Интиересно, с чем связано, что read() не возращает 0, плчему надо смотреть по коду ошибки 11……

binr ★★

(26.02.06 14:56:31 MSK)

  • Показать ответ
  • Ссылка

Re: Чтение СОМ порта… errno=11

man 2 read на тему O_NONBLOCK

  • Ссылка

Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.

(in continuation to bug https://bugs.python.org/issue25471 )

socket.recv() raises 'BlockingIOError: [Errno 11] Resource temporarily unavailable' in case, if setblocking(False) on socket returned by non-blocking socket's .accept() method and client does not sending data and didn't disconnected yet.

Not sure if I'm correct, but reading glibc doc on recv(), I think raised exception should be corrected: while code 11 correctly corresponds to EWOULDBLOCK, the misleading description 'Resource temporarily unavailable', probably, should be changed:
---
'EWOULDBLOCK'
          Nonblocking mode has been set on the socket, and the read
          operation would block.  (Normally, 'recv' blocks until there
          is input available to be read.)
---

attached file with testing server corrected for this issue

This is simply the way glibc defines the error messages.

% python3
Python 3.4.3 (default, Sep 27 2015, 15:15:25) 
[GCC 4.8.5] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import errno, os
>>> errno.EAGAIN, errno.EWOULDBLOCK
(11, 11)
>>> os.strerror(errno.EAGAIN)
'Resource temporarily unavailable'

sock.setblocking(0)
try:
    data = sock.recv(1024)
 except socket.error, e:
    if e.args[0] == errno.EWOULDBLOCK: 
          print 'EWOULDBLOCK'
else:            
   if not data:   #recv over
      sock.close()
      print 'close================='       
   else:
      print 'recv ---data---------'
      poem += data

all above code is in a loop.using non-blocking socket(just want to test ‘non-blocking socket’) to get data. But always print ‘EWOULDBLOCK’,i don’t know why?

asked Jul 25, 2012 at 9:48

zhenyuyang's user avatar

zhenyuyangzhenyuyang

1511 gold badge1 silver badge10 bronze badges

2

The socket is non-blocking so recv() will raise an exception if there is no data to read. Note that errno.EWOULDBLOCK = errno.EAGAIN = 11. This is Python’s (well the OS really) way of telling you to try the recv() again later.

I note that you close the socket each time you get this exception. That’s not going to help at all. Your code should be something like this:

import socket, errno, time

sock = socket.socket()
sock.connect(('hostname', 1234))
sock.setblocking(0)

while True:
    try:
        data = sock.recv(1024)
        if not data:
            print "connection closed"
            sock.close()
            break
        else:
            print "Received %d bytes: '%s'" % (len(data), data)
    except socket.error, e:
        if e.args[0] == errno.EWOULDBLOCK: 
            print 'EWOULDBLOCK'
            time.sleep(1)           # short delay, no tight loops
        else:
            print e
            break

For this sort of thing, the select module is usually the way to go.

answered Jul 25, 2012 at 12:10

mhawke's user avatar

mhawkemhawke

83k9 gold badges114 silver badges135 bronze badges

6

The exception is raised by design, cause you are using non-blocking IO.

The major mechanical difference is that send, recv, connect and accept can return without having done anything. You have (of course) a number of choices. You can check return code and error codes and generally drive yourself crazy.

Quoted from Python doc

If you run man errno 3, you shall see the description of EWOULDBLOCK. The exception is reasonable, because there is no data to read yet.

answered Jul 25, 2012 at 11:52

xiaowl's user avatar

xiaowlxiaowl

5,1273 gold badges27 silver badges28 bronze badges

Frequently, I transmit information to a distant operation. However, sporadically, I encounter an incoming call. Additionally, it’s essential to contemplate the possibility of several concurrent requests, as this can lead to an error due to multiple files being generated by each request simultaneously.

Table of contents

  • Fix «[Errno 11] Resource temporarily unavailable» in Python 2.x.x?
  • BlockingIOError exception ignored; should I be concerned?
  • App Engine error after Python web app is deployed — BlockingIOError: [Errno 11] Resource temporarily unavailable
  • BlockingIOError when send to non-blocking UNIX soket with SO_SNDBUF
  • Why do I get resource temporarily unavailable error on TCP?
  • What does [errno 11] resource temporarily unavailable mean?
  • What does the error message’resource temporarily unavailable’mean?

Fix «[Errno 11] Resource temporarily unavailable» in Python 2.x.x?


Question:

I possess a couple of codes:
server.py
and
talk.py
.

The intended function of
server.py
involves receiving incoming connections and processing the information transmitted by
talk.py
.

The performance is flawless when running
server.py
and
talk.py
on separate terminals of the same machine, i.e., localhost.

In
talk.py
, a string is requested. This string is then consumed by
server.py
and printed in the terminal running the program as per
server.py
.

As previously stated, the scripts are functional on an Ubuntu machine that is local.

Upon deploying my
server.py
to a GCP VM instance, it appears to run smoothly. However, upon attempting to connect my
talk.py
code to the
server.py
socket through an external web IP address on my local machine, I encountered an error code from
talk.py
.

Traceback (most recent call last):
  File "talk.py", line 11, in 
    s.connect(('35.247.28.0', port))
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 11] Resource temporarily unavailable
#server.py
# first of all import the socket library
import socket               
# next create a socket object
s = socket.socket()         
print "Socket successfully created"
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345               
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests 
# coming from other computers on the network
s.bind(('', port))        
print "socket binded to %s" %(port)
# put the socket into listening mode
s.listen(5)     
print "socket is listening"           
# a forever loop until we interrupt it or 
# an error occurs
while True:
   # Establish connection with client.
   c, addr = s.accept()     
   print 'Got connection from', addr
   # Get data from client
   """
   try:
       data = c.recv(1024)
   except IOError as e:
       print e
   """
   print data
   if not data:
     break
   # Send back reversed data to client   
   c.sendall(data)
   # send a thank you message to the client. 
   #c.send('n Thank you for sending message!!!!')
   # Close the connection with the client
   c.close()
# talk.py
# first of all import the socket library
import socket               
# next create a socket object
s = socket.socket()         
print "Socket successfully created"
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345               
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests 
# coming from other computers on the network
s.bind(('', port))        
print "socket binded to %s" %(port)
# put the socket into listening mode
s.listen(5)     
print "socket is listening"           
# a forever loop until we interrupt it or 
# an error occurs
while True:
   # Establish connection with client.
   c, addr = s.accept()     
   print 'Got connection from', addr
   print data
   if not data:
     break
   # Send back reversed data to client   
   c.sendall(data)
   # send a thank you message to the client. 
   #c.send('n Thank you for sending message!!!!')
   # Close the connection with the client
   c.close()


Solution:

It appears that there may be an issue with routing or security, rather than a problem with your code. To address this, you could try port forwarding for the Google Compute Engine instance.

An additional source is available on the topic of opening a particular port, such as 9090, in Google Compute Engine.

Python — OSError: [Errno 11] Resource temporarily, Background. I have two python processes that need to communicate with each other. The comminication is handled by a class named Pipe. I made a seperate class for this because most of the information that needs to be communicated comes in the form of dictionaries so Pipe implements a pretty simple protocol …

BlockingIOError exception ignored; should I be concerned?


Question:

To optimize the execution time of my script that comprises of 20,000 tasks involving subprocess and TCP calls, I’m utilizing the recently introduced
asyncio
feature in Python.

Although my script is running, the errors that Python outputs are causing me some worry.

Exception ignored when trying to write to the signal wakeup fd:
BlockingIOError: [Errno 11] Resource temporarily unavailable

The code will output multiple prints without throwing any errors. In the past, I faced issues such as
OSError
and lost connections to the servers. To resolve this, I implemented semaphores to restrict the number of connections to each server to 100 and a total of 700 connections.

As Python is not throwing any exceptions, the errors cannot be intercepted, although they do not appear to impact the script.

Should I worry about these errors? And if yes, how can I eliminate them from my program’s output? But, if not, what steps do I need to take to remove them?

Moreover, if the errors are critical, what is the reason behind Python ignore not raising an exception and just reporting them?


Solution:

The bottleneck seems to be caused by running multiple brief
subprocess
sessions, as indicated by the python bug tracker data.

The error message «Exception ignored when trying to write to the signal wakeup fd» is generated by the signal handler located in Modules/signalmodule.c. This issue arises because the number of SIGCHLD signals received by Python is high, as the test scripts generate more than 300 processes each second on my computer. The producer, which writes the signal number into the «self» pipe, is faster than the consumer, which is the BaseSelectorEventLoop._read_from_self callback function.

After applying the patch, I receive messages showing 140 concurrent processes. This is a significant improvement. However, in my opinion, exceeding 100 concurrent processes is not advisable, especially for processes with brief lifetimes. The limitation arises from the number of SIGCHLD per second, which is determined by the number of processes that terminate at the same second.

To avoid the errors, I limited the number of
create_subprocess_exec
es that run concurrently by modifying the code. I observed that the errors vanished when the limit was set to less than 35, but I intend to lower it to 20 as an added precaution. However, the optimal number may differ, depending on the situation.

async def myTask(stuff, semaphore, loop):
    with semaphore:
        process = await asyncio.create_subprocess_exec('short_program', loop=loop)
def taskRunner(stuffs):
    loop = asyncio.get_event_loop()
    semaphore = asyncio.Semaphore(20)  # limit how many can run at a time
    tasks = [
        asyncio.ensure_future(myTask(semaphore, loop))
        for i in range(20000)
    ]
    loop.run_until_complete(asyncio.gather(*tasks))
    loop.close()

FFMPEG BlockingIOError: [Errno 11] Resource, FFMPEG BlockingIOError: [Errno 11] Resource temporarily unavailable. I have a multiprocess pool calling different instances of ffmpeg and outputing a video file. Some of these videos are hundreds of megabytes and take a while to create. I’m seemingly getting IO bottlenecked: File «<decorator-gen-54>», …

App Engine error after Python web app is deployed — BlockingIOError: [Errno 11] Resource temporarily unavailable


Question:

My web app is set up on Python 3.7 in a standard environment. During local testing, everything runs smoothly. But, when I attempt to deploy it, I encounter an error while the app is trying to save files to a specific location (
/tmp
) that I have assigned.

BlockingIOError: [Errno 11] Resource temporarily unavailable

I’m specifying both the location to save and the name of the file.

file_num = os.urandom(10).hex()
handle, path = tempfile.mkstemp()
ytdl_format_options = {'format': 'bestaudio/best','outtmpl':path + 'song'+ file_num +'.mp3', 'quiet': True}

Uncertainty arises as to the cause of the error and whether a configuration file setting on
app.yaml
or gunicorn was missed. Despite efforts to locate the gunicorn files on the glcoud shell, they were not found in the directory.

Upon deploying my app after making new changes to files, I have observed that it functions properly only for the first attempt. Subsequently, when I try running the function again, it fails and generates an error.

Traceback (most recent call last):
  File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 279, in handle
    keepalive = self.handle_request(req, conn)
  File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 348, in handle_request
    six.reraise(*sys.exc_info())
  File "/env/lib/python3.7/site-packages/gunicorn/six.py", line 625, in reraise
    raise value
  File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 331, in handle_request
    resp.write_file(respiter)
  File "/env/lib/python3.7/site-packages/gunicorn/http/wsgi.py", line 403, in write_file
    if not self.sendfile(respiter):
  File "/env/lib/python3.7/site-packages/gunicorn/http/wsgi.py", line 393, in sendfile
    sent += sendfile(sockno, fileno, offset + sent, count)
BlockingIOError: [Errno 11] Resource temporarily unavailable


Solution:

From Filesystem:

The runtime has a complete filesystem that is mostly read-only, except for the virtual disk called
/tmp
. This virtual disk stores data in the RAM of your App Engine instance.

So:

  • The utilization of any location besides
    /tmp
    is ineffective.
  • Given the limited available space, it is crucial for your app to delete temporary files once they are no longer needed. Based on the behavior you have described, it seems that the available space may only be sufficient for storing one of your files.

When dealing with multiple parallel requests, it is important to take into account the possibility of the creation of multiple files. This can lead to errors if different requests attempt to write to these files simultaneously. To prevent this issue, it may be helpful to implement a scheme that limits the number of requests processed in parallel.

Though not completely confirmed, it seems likely that the limit could rely on the overall RAM of the instance. Therefore, the instance class set up for your app may also play a role. To verify this, experiment by temporarily setting up an instance class with more RAM to see if it resolves the issue. You could try this without clearing out the files, and it might work more than once before hitting the error.

If the aforementioned doubt is verified, opting for a suitable instance class may serve as a solution to tackle the issue.

Although all the mentioned solutions have been tried, encountering the issue is still a possibility. This may occur when the files being written are too large for the local filesystem to handle. In such a case, it is not suitable for your application. Instead, you can consider Google Cloud Storage (GCS) as an alternative for storing your files.

BlockingIOError: [Errno 35] Resource temporarily, Two things: I am familiar with a different signature for the request — which is: resp = requests.request («POST», url, data=json.dumps (payload), headers=headers, verify=False, additional-parameters>) I am seeing this issue when the URL being requested does not respond and the request times-out. Did you …

BlockingIOError when send to non-blocking UNIX soket with SO_SNDBUF


Question:

My approach for transferring data between two processes involves the use of a UNIX UDP socket that is nonblocking.

audio_s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
audio_s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 5500000)
audio_s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 5500000)
audio_s.setblocking(0)
try:
    os.remove(SOCKET_PATH)
except FileNotFoundError as e:
    pass
audio_s.bind(SOCKET_PATH)

Frequently, I transmit information to a process located remotely.

audio_s.sendto(data, REMOTE_SOCKET_PATH)

Occasionally, I come across
BlockingIOError: [Errno 11] Resource temporarily unavailable
during a call on
sendto
. It’s quite uncommon. I wonder what could be the reason for this. It seems like
Resource temporarily unavailable
is a very generic statement.

  1. Can I obtain more specific details? For instance, can I transmit buffer overflowed to receive buffer overflow remotely? Are both options feasible or just one of them?
  2. Is it possible for me to manage the number of datagrams in the send/receive buffer?
  3. What is the proper approach to handle or prevent this scenario?

If I remove line with:

audio_s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 5500000)

it works without this exception


Solution:

‘man sendto’ defines errno 11 as eagain.

The operation requested on the socket marked as non-blocking would result in blocking.

There are clear explanations available regarding the situation where a non-blocking send() only transfers some data. In such cases, is it safe to assume that EWOULDBLOCK error will be returned on the next call? Additionally, there is information about the EAGAIN error related to the usage of the Berkeley Socket API.

BlockingIOError: [Errno 11] Resource temporarily, Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.


  • Ошибка recovery your pc needs to be repaired что делать
  • Ошибка recovery your pc device needs to be repaired
  • Ошибка recovery windows 10 0xc00000e9
  • Ошибка recovery windows 10 0xc0000098
  • Ошибка recovery error code 0xc0000034