Add timeout support to proc.recv()

This commit is contained in:
Joris Vink 2019-02-26 15:22:55 +01:00
parent f4cd70956b
commit 1ebd82969c
2 changed files with 29 additions and 6 deletions

View File

@ -41,9 +41,16 @@ async def async_proc(req):
# Read until EOF (None is returned)
while True:
chunk = await proc.recv(1024)
if chunk is None:
break
try:
# Read from the process, with an optional 1 second timeout.
# The recv() call will throw a TimeoutError exception if
# the timeout has elapsed before any data was read.
chunk = await proc.recv(1024, 1000)
if chunk is None:
break
except TimeoutError as e:
print("recv() timed out: %s" % e)
continue
stdout += chunk.decode()
# Reap the process.

View File

@ -2574,17 +2574,33 @@ pyproc_reap(struct pyproc *proc, PyObject *args)
static PyObject *
pyproc_recv(struct pyproc *proc, PyObject *args)
{
Py_ssize_t len;
Py_ssize_t len;
struct pysocket_op *op;
PyObject *obj;
int timeo;
timeo = -1;
if (proc->out == NULL) {
PyErr_SetString(PyExc_RuntimeError, "stdout closed");
return (NULL);
}
if (!PyArg_ParseTuple(args, "n", &len))
if (!PyArg_ParseTuple(args, "n|i", &len, &timeo))
return (NULL);
return (pysocket_op_create(proc->out, PYSOCKET_TYPE_RECV, NULL, len));
obj = pysocket_op_create(proc->out, PYSOCKET_TYPE_RECV, NULL, len);
if (obj == NULL)
return (NULL);
op = (struct pysocket_op *)obj;
if (timeo != -1) {
op->data.timer = kore_timer_add(pysocket_op_timeout,
timeo, op, KORE_TIMER_ONESHOT);
}
return (obj);
}
static PyObject *