From ad26914631f1882eb614bef836ee796438949cdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ekl=C3=B6f?= Date: Sat, 2 Nov 2019 23:25:14 +0100 Subject: [PATCH] server: use a non-blocking socket when trying to connect When checking of a 'foot --server' instance is already running, we try to connect to the UNIX socket we're planning on listening on. In most cases, this will fail hard and fast. But under certain circumstances, we can get stuck in connect() waiting for a connection timeout. Since it should be possible to establish a connection immediately *if* there's someone actually listening on the socket, rely on the fact that connect() will fail with a EINPROGRESS if a connection can *not* be established immediately (and thus no one is listening on it). --- server.c | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/server.c b/server.c index 6ad6230e..4d3e3ca9 100644 --- a/server.c +++ b/server.c @@ -1,6 +1,7 @@ #include "server.h" #include +#include #include #include @@ -231,11 +232,29 @@ try_connect(const char *sock_path) goto err; } + /* Use non-blocking, so that we don't get stuck in connect() + * waiting for a timeout */ + int flags; + if ((flags = fcntl(fd, F_GETFL)) < 0 || + fcntl(fd, F_SETFL, flags | O_NONBLOCK)) + { + LOG_ERRNO("failed to set O_NONBLOCK"); + goto err; + } + struct sockaddr_un addr = {.sun_family = AF_UNIX}; strncpy(addr.sun_path, sock_path, sizeof(addr.sun_path) - 1); - ret = connect(fd, (const struct sockaddr *)&addr, sizeof(addr)) < 0 - ? CONNECT_FAIL : CONNECT_SUCCESS; + switch (connect(fd, (struct sockaddr *)&addr, sizeof(addr))) { + case 0: + ret = CONNECT_SUCCESS; + break; + + case -1: + LOG_DBG("connect() failed: %s", strerror(errno)); + ret = CONNECT_FAIL; + break; + } err: if (fd != -1) @@ -289,13 +308,13 @@ server_init(const struct config *conf, struct fdm *fdm, struct wayland *wayl) LOG_ERRNO("%s: failed to listen", addr.sun_path); goto err; } - + server = malloc(sizeof(*server)); *server = (struct server) { .conf = conf, .fdm = fdm, .wayl = wayl, - + .fd = fd, .sock_path = sock_path,