From 983702511918b972704eb591dcb28b45fd56ae9b Mon Sep 17 00:00:00 2001 From: theidexisted Date: Thu, 9 Dec 2021 11:36:56 +0800 Subject: [PATCH] Reduce one syscal for fcntl According to the man page: https://man7.org/linux/man-pages/man2/socket.2.html Since Linux 2.6.27, the type argument serves a second purpose: in addition to specifying a socket type, it may include the bitwise OR of any of the following values, to modify the behavior of socket(): SOCK_NONBLOCK Set the O_NONBLOCK file status flag on the open file description (see open(2)) referred to by the new file descriptor. Using this flag saves extra calls to fcntl(2) to achieve the same result. --- src/nc_proxy.c | 9 +-------- src/nc_server.c | 10 +--------- 2 files changed, 2 insertions(+), 17 deletions(-) diff --git a/src/nc_proxy.c b/src/nc_proxy.c index 38cdd9e6..132deb96 100644 --- a/src/nc_proxy.c +++ b/src/nc_proxy.c @@ -128,7 +128,7 @@ proxy_listen(struct context *ctx, struct conn *p) ASSERT(p->proxy); - p->sd = socket(p->family, SOCK_STREAM, 0); + p->sd = socket(p->family, SOCK_STREAM | SOCK_NONBLOCK, 0); if (p->sd < 0) { log_error("socket failed: %s", strerror(errno)); return NC_ERROR; @@ -166,13 +166,6 @@ proxy_listen(struct context *ctx, struct conn *p) return NC_ERROR; } - status = nc_set_nonblocking(p->sd); - if (status < 0) { - log_error("set nonblock on p %d on addr '%.*s' failed: %s", p->sd, - pool->addrstr.len, pool->addrstr.data, strerror(errno)); - return NC_ERROR; - } - status = event_add_conn(ctx->evb, p); if (status < 0) { log_error("event add conn p %d on addr '%.*s' failed: %s", diff --git a/src/nc_server.c b/src/nc_server.c index dab6a79b..c2a15c7d 100644 --- a/src/nc_server.c +++ b/src/nc_server.c @@ -483,7 +483,7 @@ server_connect(struct context *ctx, struct server *server, struct conn *conn) log_debug(LOG_VVERB, "connect to server '%.*s'", server->pname.len, server->pname.data); - conn->sd = socket(conn->family, SOCK_STREAM, 0); + conn->sd = socket(conn->family, SOCK_STREAM | SOCK_NONBLOCK, 0); if (conn->sd < 0) { log_error("socket for server '%.*s' failed: %s", server->pname.len, server->pname.data, strerror(errno)); @@ -491,14 +491,6 @@ server_connect(struct context *ctx, struct server *server, struct conn *conn) goto error; } - status = nc_set_nonblocking(conn->sd); - if (status != NC_OK) { - log_error("set nonblock on s %d for server '%.*s' failed: %s", - conn->sd, server->pname.len, server->pname.data, - strerror(errno)); - goto error; - } - if (server->pname.data[0] != '/') { status = nc_set_tcpnodelay(conn->sd); if (status != NC_OK) {