Skip to content

Commit

Permalink
samples: net: echo_async_select: Use read()/write() if possible
Browse files Browse the repository at this point in the history
If build with full POSIX API, use read()/write() instead of
recv()/send() calls for sockets.

We have read()/write() support for a while, but no samples/tests
actually performed at least a build test for it (so it will be
done now).

Fixes: #25407
Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
  • Loading branch information
pfalcon authored and carlescufi committed May 20, 2020
1 parent c6a19a2 commit 8af7187
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
1 change: 1 addition & 0 deletions samples/net/sockets/echo_async_select/prj.conf
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# General config
CONFIG_NEWLIB_LIBC=y
CONFIG_MAIN_STACK_SIZE=1200
CONFIG_POSIX_API=y

# Networking config
CONFIG_NETWORKING=y
Expand Down
19 changes: 14 additions & 5 deletions samples/net/sockets/echo_async_select/src/socket_echo_select.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,20 @@
#include <unistd.h>
#include <fcntl.h>

/* Generic read()/write() is available in POSIX config, so use it. */
#define READ(fd, buf, sz) read(fd, buf, sz)
#define WRITE(fd, buf, sz) write(fd, buf, sz)

#else

#include <fcntl.h>
#include <net/socket.h>
#include <kernel.h>

/* Generic read()/write() are not defined, so use socket-specific recv(). */
#define READ(fd, buf, sz) recv(fd, buf, sz, 0)
#define WRITE(fd, buf, sz) send(fd, buf, sz, 0)

#endif

/* For Zephyr, keep max number of fd's in sync with max poll() capacity */
Expand Down Expand Up @@ -178,17 +186,18 @@ void main(void)
addr_str, client);
if (pollfds_add(client) < 0) {
static char msg[] = "Too many connections\n";
send(client, msg, sizeof(msg) - 1, 0);
WRITE(client, msg, sizeof(msg) - 1);
close(client);
} else {
setblocking(client, false);
}
} else {
char buf[128];
int len = recv(fd, buf, sizeof(buf), 0);
int len = READ(fd, buf, sizeof(buf));
if (len <= 0) {
if (len < 0) {
printf("error: recv: %d\n", errno);
printf("error: RECV: %d\n",
errno);
}
error:
pollfds_del(fd);
Expand All @@ -207,10 +216,10 @@ void main(void)
setblocking(fd, true);

for (p = buf; len; len -= out_len) {
out_len = send(fd, p, len, 0);
out_len = WRITE(fd, p, len);
if (out_len < 0) {
printf("error: "
"send: %d\n",
"WRITE: %d\n",
errno);
goto error;
}
Expand Down

0 comments on commit 8af7187

Please sign in to comment.