Skip to content

Commit 9fd02e1

Browse files
committed
modsocket: Add setblocking() method.
1 parent 0f836ef commit 9fd02e1

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

unix/modsocket.c

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include <assert.h>
33
#include <string.h>
44
#include <unistd.h>
5+
#include <fcntl.h>
56
#include <sys/stat.h>
67
#include <sys/types.h>
78
#include <sys/socket.h>
@@ -179,6 +180,22 @@ STATIC mp_obj_t socket_setsockopt(uint n_args, const mp_obj_t *args) {
179180
}
180181
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_setsockopt_obj, 4, 4, socket_setsockopt);
181182

183+
STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
184+
mp_obj_socket_t *self = self_in;
185+
int val = mp_obj_is_true(flag_in);
186+
int flags = fcntl(self->fd, F_GETFL, 0);
187+
RAISE_ERRNO(flags, errno);
188+
if (val) {
189+
flags &= ~O_NONBLOCK;
190+
} else {
191+
flags |= O_NONBLOCK;
192+
}
193+
flags = fcntl(self->fd, F_SETFL, flags);
194+
RAISE_ERRNO(flags, errno);
195+
return mp_const_none;
196+
}
197+
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
198+
182199
STATIC mp_obj_t socket_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
183200
int family = AF_INET;
184201
int type = SOCK_STREAM;
@@ -216,6 +233,7 @@ STATIC const mp_map_elem_t microsocket_locals_dict_table[] = {
216233
{ MP_OBJ_NEW_QSTR(MP_QSTR_recv), (mp_obj_t)&socket_recv_obj },
217234
{ MP_OBJ_NEW_QSTR(MP_QSTR_send), (mp_obj_t)&socket_send_obj },
218235
{ MP_OBJ_NEW_QSTR(MP_QSTR_setsockopt), (mp_obj_t)&socket_setsockopt_obj },
236+
{ MP_OBJ_NEW_QSTR(MP_QSTR_setblocking), (mp_obj_t)&socket_setblocking_obj },
219237
{ MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&socket_close_obj },
220238
#if MICROPY_SOCKET_EXTRA
221239
{ MP_OBJ_NEW_QSTR(MP_QSTR_recv), (mp_obj_t)&mp_stream_read_obj },

unix/qstrdefsport.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ Q(listen)
3838
Q(accept)
3939
Q(recv)
4040
Q(setsockopt)
41+
Q(setblocking)
4142

4243
Q(AF_UNIX)
4344
Q(AF_INET)

0 commit comments

Comments
 (0)