diff -r 39fe86ae4db0 -r ff576305ae6e src/server/daemon/main.c --- a/src/server/daemon/main.c Sun Nov 13 12:58:25 2022 +0100 +++ b/src/server/daemon/main.c Wed Nov 16 12:14:45 2022 +0100 @@ -33,6 +33,8 @@ #include #include #include +#include +#include #include "../util/pool.h" #include "../public/nsapi.h" @@ -49,7 +51,12 @@ #include "configmanager.h" -static int std_pipe_fds[2]; +#define LOG_THREAD_STACK_SIZE 32768 +#define LOG_THREAD_MAX_POLL_FAILS 10 +#define LOG_THREAD_READ_BUF 2048 + +static int std_out[2]; +static int std_err[2]; static WSBool is_daemon; void test() { @@ -93,25 +100,97 @@ //exit(EXIT_SUCCESS); } -void* log_pipe_thread(void *data) { - //FILE *log_out = fopen("log.txt", "a"); +static void set_pipe_nonblocking(int fd) { + int flags = 0; + flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); +} + +static char log_pipe_readbuf[LOG_THREAD_READ_BUF]; +static char log_pipe_stdout_buf[LOG_THREAD_READ_BUF]; +static char log_pipe_stderr_buf[LOG_THREAD_READ_BUF]; +static size_t log_pipe_stdout_tmp_pos = 0; +static size_t log_pipe_stderr_tmp_pos = 0; - char buf[1024]; - ssize_t r; - while((r = read(std_pipe_fds[0], buf, 1024)) > 0) { - //fwrite(buf, 1, r, log_out); - //fflush(log_out); +static int log_pipe(const char *name, int fd, char *buf, size_t *pos) { + ssize_t r = read(fd, log_pipe_readbuf, 2); + if(r <= 0) { + return 1; + } + + char *tmp = buf; + int tmplen = *pos; + + int s = 0; + for(int i=0;i 0) { + log_message(name, "%.*s%.*s", tmplen, tmp, i-s, log_pipe_readbuf + s); + } + tmplen = 0; + *pos = 0; + s = i+1; + } + } + + int remaining = r - s; + if(tmplen + remaining >= LOG_THREAD_READ_BUF) { + log_message(name, "%.*s%.*s", tmplen, tmp, remaining, log_pipe_readbuf + s); + *pos = 0; + } else if(remaining > 0) { + memcpy(buf + *pos, log_pipe_readbuf + s, remaining); + *pos += remaining; } + + return 0; +} - //fclose(log_out); +void* log_pipe_thread(void *data) { + set_pipe_nonblocking(std_out[0]); + set_pipe_nonblocking(std_err[0]); + + struct pollfd fds[2]; + fds[0].fd = std_out[0]; + fds[0].events = POLLIN; + fds[1].fd = std_err[0]; + fds[1].events = POLLIN; + int poll_fails = 0; + for(;;) { + if(poll(fds, 1, 1000000) < 0) { + if(errno == EINTR) { + continue; + } + log_ereport(LOG_FAILURE, "log thread poll failed: %s", strerror(errno)); + if(poll_fails++ > LOG_THREAD_MAX_POLL_FAILS) { + break; + } + } + + // check stdout + if(fds[0].revents & POLLIN) { + if(log_pipe("stdout", fds[0].fd, log_pipe_stdout_buf, &log_pipe_stdout_tmp_pos)) { + break; + } + } + + // check stderr + if(fds[1].revents & POLLIN) { + if(log_pipe("stderr", fds[0].fd, log_pipe_stderr_buf, &log_pipe_stderr_tmp_pos)) { + break; + } + } + } + + log_ereport(LOG_INFORM, "log thread end"); + return NULL; } int main(int argc, char **argv) { //test(); - /* if the -c parameter is specified, we don't create a daemon */ + // if the -c parameter is specified, we don't create a daemon is_daemon = 1; for(int i=0;i