#include #include #include #include #include #include #include "logging.h" #include "multicast.h" #include "unixsock.h" #define BUF_SIZE 256 void selector() { fd_set fdsel; char *buf = malloc(BUF_SIZE); if (buf == NULL) { log_print(LOG_ERROR, "selector: out of memory"); return; } int usock = sock_init(); if (usock < 0) return; int msock = mcast_init(); if (msock < 0) return; int usock_con = -1; while (1) { struct timeval tv; FD_ZERO(&fdsel); FD_SET(usock, &fdsel); FD_SET(msock, &fdsel); if (usock_con != -1) FD_SET(usock_con, &fdsel); tv.tv_sec = 60; tv.tv_usec = 0; int ret = select(64, &fdsel, NULL, NULL, &tv); if (ret < 0) { log_print(LOG_ERROR, "selector: select()"); continue; } else if (ret == 0) { mcast_send(msock, "KEEPALIVE", 10); } else if (FD_ISSET(usock, &fdsel)) { if (usock_con != -1) { log_print(LOG_INFO, "selector: unix socket overflow"); close(usock_con); } usock_con = accept(usock, NULL, NULL); if (usock_con == -1) log_print(LOG_ERROR, "selector: accept()"); } else if (usock_con != -1 && FD_ISSET(usock_con, &fdsel)) { int len = read(usock_con, buf, BUF_SIZE); if (len > 0) mcast_send(msock, buf, len); if (!strncmp(buf, "DELETE ", 7)) { log_print(LOG_DEBUG, "delete '%s'", buf +7); // exec unlink } else { log_print(LOG_DEBUG, "recv unknown cmd via unix socket: '%s'", buf); } close(usock_con); usock_con = -1; } else if (FD_ISSET(msock, &fdsel)) { int len = read(msock, buf, BUF_SIZE); if (len <= 0) { log_print(LOG_ERROR, "selector: multicast sock closed?"); } else if (!strncmp(buf, "KEEPALIVE", 10)) { } else if (!strncmp(buf, "DELETE ", 7)) { log_print(LOG_DEBUG, "delete '%s'", buf +7); // exec unlink } else { log_print(LOG_DEBUG, "recv unknown cmd via multicast: '%s'", buf); } } } msock_close(msock); sock_close(usock); }