static int epoll_init(void) { int epoll_fd = epoll_create(EPOLL_NUM); MNLD_DATA_T *obj = &mnld_data; if (epoll_fd < 0) return -1; if (obj->cur_accept_socket != C_INVALID_FD) { if (epoll_add(epoll_fd, obj->cur_accept_socket)) return -1; } if (obj->sig_rcv_fd != C_INVALID_FD) { if (epoll_add(epoll_fd, obj->sig_rcv_fd)) return -1; } if (obj->mnl_rcv_fd != C_INVALID_FD) { if (epoll_add(epoll_fd, obj->mnl_rcv_fd)) return -1; } obj->epoll_fd = epoll_fd; return 0; }
int parent_main(pid_t child_pid) { int epfd; int sigfd; int status; sigset_t sigs; if (sigfillset(&sigs) == -1) { ERRMSG("sigfillset() failed"); goto kill_child; } if (sigprocmask(SIG_SETMASK, &sigs, NULL) == -1) { ERRMSG("sigprocmask() failed"); goto kill_child; } if ((sigfd = signalfd(-1, &sigs, SFD_NONBLOCK)) == -1) { ERRMSG("signalfd() failed"); goto kill_child; } if ((epfd = epoll_create(1)) == -1) { ERRMSG("epoll_create() failed"); goto kill_child; } if (epoll_add(epfd, sigfd, EPOLLIN) == -1) { ERRMSG("epoll_add() failed"); goto kill_child; } if (epoll_add(epfd, STDIN_FILENO, 0) == -1) { ERRMSG("epoll_add() failed"); goto kill_child; } for (;;) { int i; enum HANDLE_RESULT handle_ret; struct epoll_event e[3]; int nfd = epoll_wait(epfd, e, sizeof(e) / sizeof(struct epoll_event), 100); if (nfd == -1) { ERRMSG("epoll_wait() failed"); goto kill_child; } if (nfd == 0) { int ret = waitpid(child_pid, &status, WNOHANG); if (ret == -1) { ERRMSG("waitpid() failed"); goto kill_child; } if (ret != 0) { goto child_exited; } continue; } for (i = 0; i < nfd; i++) { int fd = e[i].data.fd; if (fd == sigfd) { handle_ret = handle_signal(fd, child_pid); } else { handle_ret = handle_in_eof(fd, child_pid); } switch(handle_ret) { case KILL_CHILD: goto kill_child; case WAIT_CHILD_EXIT: goto wait_child_exit; } } } kill_child: if (kill(child_pid, SIGKILL) == -1) { ERR_EXIT("kill() failed"); } wait_child_exit: if (waitpid(child_pid, &status, 0) == -1) { ERR_EXIT("waitpid() failed"); } child_exited: if (WIFEXITED(status)) { return WEXITSTATUS(status); } if (WIFSIGNALED(status)) { return WTERMSIG(status) + 128; } return 1; }
void My_epoll::handle_query() { struct epoll_event events[EPOLLSIZE]; int epollfd=epoll_create(EPOLLSIZE); if(epollfd==-1) { m_log.error("epoll create failed"); } socket_init(); set_nonblock(server_sock); QUERY_HANDLE::Query_handle handle(m_conf,&m_log); epoll_add(epollfd,server_sock,EPOLLIN|EPOLLET); std::cout<<"server wait for connecting......."<<std::endl; m_log.notice("server wait for connecting........."); while(1) { int ret=epoll_wait(epollfd,events,EPOLLSIZE,-1); for(int index=0;index<ret;index++) { if(events[index].data.fd==server_sock) { int fd_client=socket_accept(); set_nonblock(fd_client); handle(fd_client); } } } }
int main(int argv,char **args) { int ret,epfd,nfds,server_socket_fd,i,index; struct epoll_event events[256]; int count; server_socket_fd = server_start(); if(server_socket_fd<0) { return 0; } set_non_blocking(server_socket_fd); epfd = epoll_create(1024); set_non_blocking(epfd); epoll_add(epfd,server_socket_fd); struct http_request_r *r=NULL,*p=NULL; while(1) { nfds=epoll_wait(epfd,events,20,500); for(i=0;i<nfds;i++) { if(events[i].data.fd==server_socket_fd) { onAccept(epfd,events[i],&r); } else if(events[i].events&EPOLLIN) { onData(epfd,events[i],&r); } } } }
static int event_add(ohc_request_t *r, req_handler_f *handler, int event, time_t timeout) { uint32_t epoll_ev = (event == OHC_EV_READ) ? EPOLLIN : EPOLLOUT; int epoll_fd = r->worker_thread ? r->worker_thread->epoll_fd : master_epoll_fd; ohc_timer_t *timer; if(r->events == event) { timer_update(&r->tnode, timeout); } else if(r->events) { if(epoll_mod(epoll_fd, r->sock_fd, epoll_ev, r) != 0) { return OHC_ERROR; } if(timer_update(&r->tnode, timeout) != 0) { return OHC_ERROR; } } else { timer = r->worker_thread ? &r->worker_thread->timer : &master_timer; if(epoll_add(epoll_fd, r->sock_fd, epoll_ev, r) != 0) { return OHC_ERROR; } if(timer_add(timer, &r->tnode, timeout) != 0) { return OHC_ERROR; } } r->events = event; r->event_handler = handler; return OHC_OK; }
/** * Process read (client) command. */ static void do_read_cmd (const int epollfd, struct command * command) { uint8_t buf[BUFLEN] = { 0 }; ssize_t readbytes; /* read command(s) from client */ if ((readbytes = read (command->cfd, buf, BUFLEN)) <= 0) { if (readbytes == 0) { /* EOF, client closed socket */ ; } else { perror ("ctrlsock read error"); } close (command->cfd); /* also removes from epoll */ } /* send from cache or defer relay */ else { uint8_t **services = extract_cmds (buf); for (; services && *services; ++services) { uint8_t *service = *services; /* try sending from cache, upon miss defer remote host read */ if (!cache_sendfile (command->cfd, service)) { int rsock; if ((rsock = connect_remote_host (service, readbytes)) < 0) { warn ("could not connect to host"); return; } struct command *newcmd = calloc (1, sizeof (struct command)); /* add command to read remote host data to event queue */ newcmd->cmd = READ_REMOTE; newcmd->cfd = command->cfd; newcmd->rfd = rsock; newcmd->service = service; /* add command to event queue */ epoll_add (epollfd, newcmd); } } /* processed all commands, back to READ_CMD */ struct command *readcmd = calloc (1, sizeof (struct command)); readcmd->cmd = READ_CMD; readcmd->cfd = command->cfd; epoll_mod (epollfd, readcmd); } }
static bool linuxraw_joypad_init(void *data) { unsigned i; settings_t *settings = config_get_ptr(); if (!epoll_new(true)) return false; (void)data; for (i = 0; i < MAX_USERS; i++) { char path[PATH_MAX_LENGTH] = {0}; autoconfig_params_t params = {{0}}; struct linuxraw_joypad *pad = (struct linuxraw_joypad*)&linuxraw_pads[i]; if (!pad) continue; params.idx = i; pad->fd = -1; pad->ident = settings->input.device_names[i]; snprintf(path, sizeof(path), "/dev/input/js%u", i); if (linuxraw_joypad_init_pad(path, pad)) { strlcpy(params.name, pad->ident, sizeof(params.name)); strlcpy(params.driver, "linuxraw", sizeof(params.driver)); /* TODO - implement VID/PID? */ input_config_autoconfigure_joypad(¶ms); linuxraw_poll_pad(pad); } else input_config_autoconfigure_joypad(¶ms); } g_inotify = inotify_init(); if (g_inotify >= 0) { fcntl(g_inotify, F_SETFL, fcntl(g_inotify, F_GETFL) | O_NONBLOCK); inotify_add_watch(g_inotify, "/dev/input", IN_DELETE | IN_CREATE | IN_ATTRIB); epoll_add(g_inotify, NULL); } g_hotplug = true; return true; }
static bool udev_input_add_device(udev_input_t *udev, const char *devnode, device_handle_cb cb) { int fd; udev_input_device_t **tmp; udev_input_device_t *device = NULL; struct stat st = {0}; if (stat(devnode, &st) < 0) return false; fd = open(devnode, O_RDONLY | O_NONBLOCK); if (fd < 0) return false; device = (udev_input_device_t*)calloc(1, sizeof(*device)); if (!device) goto error; device->fd = fd; device->dev = st.st_dev; device->handle_cb = cb; strlcpy(device->devnode, devnode, sizeof(device->devnode)); /* Touchpads report in absolute coords. */ if (cb == udev_handle_touchpad && (ioctl(fd, EVIOCGABS(ABS_X), &device->state.touchpad.info_x) < 0 || ioctl(fd, EVIOCGABS(ABS_Y), &device->state.touchpad.info_y) < 0)) goto error; tmp = ( udev_input_device_t**)realloc(udev->devices, (udev->num_devices + 1) * sizeof(*udev->devices)); if (!tmp) goto error; tmp[udev->num_devices++] = device; udev->devices = tmp; epoll_add(&udev->epfd, fd, device); return true; error: close(fd); if (device) free(device); return false; }
void add_fd_2_efd(int fd) { epoll_add(epfd, fd, EPOLLIN); fcntl(fd, F_SETFL, O_RDWR|O_NONBLOCK); struct conn *curconn = &acon[fd]; curconn->fd = fd; curconn->send_len = 0; memset(curconn->peerip, 0, sizeof(curconn->peerip)); mybuff_reinit(&(curconn->send_buff)); mybuff_reinit(&(curconn->recv_buff)); uint32_t ip = getpeerip(fd); ip2str(curconn->peerip, ip); LOG(glogfd, LOG_DEBUG, "fd [%d] [%s]set ok %d\n", fd, curconn->peerip, curconn->fd); }
/** * Process all incoming connections. */ static void do_accept (const int listensock, const int epollfd) { for (;;) { int client_socket; struct sockaddr_storage peer_addr; socklen_t peer_addr_len; struct command *command; peer_addr_len = sizeof (peer_addr); /* TODO use accept4() instead of accept and mk_nonblock, saves calls to * fcntl and userspace flag bit twiddling. */ #if 0 client_socket = accept (listensock, (struct sockaddr *) &peer_addr, &peer_addr_len); #endif client_socket = accept4 (listensock, (struct sockaddr *) &peer_addr, &peer_addr_len, SOCK_NONBLOCK); if (client_socket < 0) { if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { /* processed all incoming connections */ break; } else { perror ("do_accept"); break; } } #if 0 if (mk_nonblock (client_socket) < 0) { err (1, "Could not make client socket non-blocking"); } #endif /* create read client command */ command = calloc (1, sizeof (struct command)); command->cmd = READ_CMD; command->cfd = client_socket; /* add command to epoll event queue */ epoll_add (epollfd, command); } }
static bool linuxraw_joypad_init_pad(const char *path, struct linuxraw_joypad *pad) { settings_t *settings = config_get_ptr(); if (pad->fd >= 0) return false; /* Device can have just been created, but not made accessible (yet). IN_ATTRIB will signal when permissions change. */ if (access(path, R_OK) < 0) return false; pad->fd = open(path, O_RDONLY | O_NONBLOCK); *pad->ident = '\0'; if (pad->fd >= 0) { if (ioctl(pad->fd, JSIOCGNAME(sizeof(settings->input.device_names[0])), pad->ident) >= 0) { RARCH_LOG("[Device]: Found pad: %s on %s.\n", pad->ident, path); if (g_hotplug) { char msg[512] = {0}; snprintf(msg, sizeof(msg), "Device #%u (%s) connected.", (unsigned)(pad - linuxraw_pads), pad->ident); runloop_msg_queue_push(msg, 0, 60, false); } } else RARCH_ERR("[Device]: Didn't find ident of %s.\n", path); if (!epoll_add(pad->fd, pad)) goto error; return true; } error: RARCH_ERR("[Device]: Failed to open pad %s (error: %s).\n", path, strerror(errno)); return false; }
int onAccept(int epfd,struct epoll_event ev,struct http_request_r **r) { int server_socket_fd,client_socket_fd,addrlen,ret; struct sockaddr_in client_addr; server_socket_fd = ev.data.fd; client_socket_fd = accept(server_socket_fd,(struct sockaddr *)&client_addr,&addrlen); if(client_socket_fd<0) { perror("accpet error"); return -1; } add_http_request(r,client_socket_fd); struct http_request_r *q; q = *r; set_non_blocking(client_socket_fd); epoll_add(epfd,client_socket_fd); return 0; }
int main(int argc, char *argv[]) { _bcc_status bcc; void *buf; bool client = false; int count_read; int count_written; int count_xferred; bool e_ldone; bool e_pwu; int err; int ferr; short filenumr; short filenums; int inx; int loop = 10; char *p; char recv_buffer[BUFSIZ]; char send_buffer[BUFSIZ]; int socka; int sockc; int sockl; SB_Tag_Type tag; short tfilenum; int timeout = -1; short wakeup; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "-v", TA_Bool, TA_NOMAX, &verbose }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages TEST_CHK_FEOK(ferr); if (client) { ferr = BFILE_OPEN_((char *) "$srv", (short) 4, &filenums, 0, 0, 1, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { sprintf(send_buffer, "inx=%d", inx); bcc = BWRITEREADX(filenums, send_buffer, (short) (strlen(send_buffer) + 1), BUFSIZ, &count_read, 1); TEST_CHK_BCCEQ(bcc); tfilenum = -1; bcc = BAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_BCCEQ(bcc); } p = strchr(send_buffer, ':'); *p = 0; p++; strcpy(host, send_buffer); port = (unsigned short) atoi(p); if (verbose) printf("server returned host=%s, port=%d\n", host, port); if (verbose) printf("client connecting up\n"); // connect up, and setup fds epoll_init(); sockc = do_sock_connect(); pin_main = 1; proc_register_group_pin(-1, pin_main); epoll_add(sockc); do_thread_create(); bcc = BWRITEREADX(filenums, NULL, 0, BUFSIZ, &count_read, 1); TEST_CHK_BCCEQ(bcc); usleep(10000); e_pwu = false; e_ldone = false; for (;;) { wakeup = XWAIT(LDONE | PWU, -1); if (wakeup & PWU) { e_pwu = true; do_io_comp(); } if (wakeup & LDONE) { e_ldone = true; timeout = -1; tfilenum = -1; bcc = BAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_BCCEQ(bcc); } if (e_ldone && e_pwu) break; } do_thread_join(); if (verbose) printf("client closing\n"); ferr = BFILE_CLOSE_(filenums, 0); TEST_CHK_FEOK(ferr); printf("if there were no asserts, all is well\n"); } else { sockl = do_sock_listen(); assert(sockl != -1); ferr = BFILE_OPEN_((char *) "$RECEIVE", 8, &filenumr, 0, 0, 1, 1, 1, // no sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { bcc = BREADUPDATEX(filenumr, recv_buffer, BUFSIZ, &count_read, 1); TEST_CHK_BCCEQ(bcc); tfilenum = filenumr; bcc = BAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_BCCEQ(bcc); assert(tag == 1); sprintf(recv_buffer, "%s:%d\n", host, port); count_read = (short) (strlen(recv_buffer) + 1); bcc = BREPLYX(recv_buffer, count_read, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_BCCEQ(bcc); } if (verbose) printf("server accepting\n"); socka = do_sock_accept(sockl); err = (int) write(socka, recv_buffer, 1); assert(err != -1); for (inx = 0; inx < 1; inx++) { bcc = BREADUPDATEX(filenumr, recv_buffer, BUFSIZ, &count_read, 1); TEST_CHK_BCCEQ(bcc); tfilenum = filenumr; bcc = BAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_BCCEQ(bcc); bcc = BREPLYX(recv_buffer, 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_BCCEQ(bcc); } if (verbose) printf("server closing\n"); ferr = BFILE_CLOSE_(filenumr, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
static int launch_daemon_thread(void) { pid_t pid; int p2c[2] = {C_INVALID_FD,C_INVALID_FD}; int c2p[2] = {C_INVALID_FD,C_INVALID_FD}; MND_TRC(); if (pipe(p2c) < 0 || pipe(c2p) < 0) { MND_ERR("create pipe: %d (%s)\n", errno, strerror(errno)); goto error; } else { int flags; flags = fcntl(p2c[0], F_GETFD); fcntl(p2c[0], F_SETFD, (flags & ~FD_CLOEXEC)); flags = fcntl(p2c[1], F_GETFD); fcntl(p2c[1], F_SETFD, (flags & ~FD_CLOEXEC)); flags = fcntl(c2p[0], F_GETFD); fcntl(c2p[0], F_SETFD, (flags & ~FD_CLOEXEC)); flags = fcntl(c2p[1], F_GETFD); fcntl(c2p[1], F_SETFD, (flags & ~FD_CLOEXEC)); } if ((pid = fork()) < 0) { MND_ERR("fork fails: %d (%s)\n", errno, strerror(errno)); goto error; } else if (pid == 0) { /*child process*/ int err; char fd0[12] = {0}; char fd1[12] = {0}; char char_assist_data_bit_map[12] = {0}; char *argv[] = {"/system/xbin/libmnlp", "libmnlp", fd0, fd1, char_assist_data_bit_map}; close(p2c[1]); /*close the write channel in p2c because the pipe is used for reading data from parent*/ close(c2p[0]); /*close the read channel in c2p because the pipe is used for writing data to parent*/ snprintf(fd0, sizeof(fd0), "%d", p2c[0]); snprintf(fd1, sizeof(fd1), "%d", c2p[1]); snprintf(char_assist_data_bit_map, sizeof(char_assist_data_bit_map), "%d", assist_data_bit_map); MND_MSG("execute: %s %s %s %s %s\n", argv[0], argv[1], argv[2], argv[3], argv[4]); err = execl(argv[0], argv[1], argv[2], argv[3], argv[4], NULL); if (err == -1) { MND_MSG("execl error: %s\n", strerror(errno)); return -1; } return 0; } else { /*parent process*/ MNLD_DATA_T *obj = &mnld_data; close(p2c[0]); /*close the read channel in p2c because the pipe is used for writing data to child*/ close(c2p[1]); /*close the write channel in c2p because the pipe is used for reading data from child*/ mnld_monitor.pid = pid; obj->mnl_rcv_fd = c2p[0]; obj->mnl_snd_fd = p2c[1]; if (epoll_add(obj->epoll_fd, obj->mnl_rcv_fd)) { MND_MSG("add mnl_rcv_fd fails: %d (%s)\n", errno, strerror(errno)); return -1; } MND_MSG("mnl_pid = %d\n", pid); mnl_set_alarm(MNL_ALARM_INIT); return 0; } error: if (p2c[0] != C_INVALID_FD) { close(p2c[0]); } if (p2c[1] != C_INVALID_FD) { close(p2c[1]); } if (c2p[0] != C_INVALID_FD) { close(c2p[0]); } if (c2p[1] != C_INVALID_FD) { close(c2p[1]); } return -1; }
int main(int argc, char **argv) { prevent_leaked_file_descriptors(); bool mount_proc = false; bool mount_dev = false; const char *username = "******"; const char *hostname = "playpen"; long timeout = 0; long memory_limit = 128; struct bind_list *binds = NULL, *binds_tail = NULL; char *devices = NULL; char *syscalls = NULL; const char *syscalls_file = NULL; const char *learn_name = NULL; static const struct option opts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 'v' }, { "mount-proc", no_argument, 0, 'p' }, { "mount-dev", no_argument, 0, 0x100 }, { "bind", required_argument, 0, 'b' }, { "bind-rw", required_argument, 0, 'B' }, { "user", required_argument, 0, 'u' }, { "hostname", required_argument, 0, 'n' }, { "timeout", required_argument, 0, 't' }, { "memory-limit", required_argument, 0, 'm' }, { "devices", required_argument, 0, 'd' }, { "syscalls", required_argument, 0, 's' }, { "syscalls-file", required_argument, 0, 'S' }, { "learn", required_argument, 0, 'l' }, { 0, 0, 0, 0 } }; for (;;) { int opt = getopt_long(argc, argv, "hvpb:B:u:n:t:m:d:s:S:l:", opts, NULL); if (opt == -1) break; switch (opt) { case 'h': usage(stdout); case 'v': printf("%s %s\n", program_invocation_short_name, VERSION); return 0; case 'p': mount_proc = true; break; case 0x100: mount_dev = true; break; case 'b': case 'B': if (binds) { binds_tail->next = bind_list_alloc(optarg, opt == 'b'); binds_tail = binds_tail->next; } else { binds = binds_tail = bind_list_alloc(optarg, opt == 'b'); } break; case 'u': username = optarg; break; case 'n': hostname = optarg; break; case 't': timeout = strtolx_positive(optarg, "timeout"); break; case 'm': memory_limit = strtolx_positive(optarg, "memory limit"); break; case 'd': devices = optarg; break; case 's': syscalls = optarg; break; case 'S': syscalls_file = optarg; break; case 'l': learn_name = optarg; break; default: usage(stderr); } } if (argc - optind < 2) { usage(stderr); } const char *root = argv[optind]; optind++; scmp_filter_ctx ctx = seccomp_init(learn_name ? SCMP_ACT_TRACE(0) : SCMP_ACT_KILL); if (!ctx) errx(EXIT_FAILURE, "seccomp_init"); if (syscalls_file) { char name[SYSCALL_NAME_MAX]; FILE *file = fopen(syscalls_file, "r"); if (!file) err(EXIT_FAILURE, "failed to open syscalls file: %s", syscalls_file); while (fgets(name, sizeof name, file)) { char *pos; if ((pos = strchr(name, '\n'))) *pos = '\0'; check(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, get_syscall_nr(name), 0)); } fclose(file); } check(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, __NR_execve, 0)); if (syscalls) { for (char *s_ptr = syscalls, *saveptr; ; s_ptr = NULL) { const char *syscall = strtok_r(s_ptr, ",", &saveptr); if (!syscall) break; check(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, get_syscall_nr(syscall), 0)); } } int epoll_fd = epoll_create1(EPOLL_CLOEXEC); check_posix(epoll_fd, "epoll_create1"); sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGHUP); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); check_posix(sigprocmask(SIG_BLOCK, &mask, NULL), "sigprocmask"); int sig_fd = signalfd(-1, &mask, SFD_CLOEXEC); check_posix(sig_fd, "signalfd"); epoll_add(epoll_fd, sig_fd, EPOLLIN); int pipe_in[2]; int pipe_out[2]; int pipe_err[2]; check_posix(pipe(pipe_in), "pipe"); check_posix(pipe(pipe_out), "pipe"); set_non_blocking(pipe_out[0]); check_posix(pipe(pipe_err), "pipe"); set_non_blocking(pipe_err[0]); int rc = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &(struct epoll_event){ .data.fd = STDIN_FILENO, .events = EPOLLIN });
int main (int argc, char **argv) { srand (time (NULL)); int port = 8080; int work = 4; sighandleall (&signal_handler, SA_RESTART); argv0 = *argv; setname ("cws[master]"); int selfpiperead; { int pipefd[2]; if (pipe (pipefd) == -1) { die("pipe"); } selfpipe = pipefd[1]; selfpiperead = pipefd[0]; } worker_init (port, "file"); spawn_workers (work); tcgetattr (STDIN_FILENO, &old_term); atexit (&cleanup); setterm(); int epollfd = epoll(); epoll_add (epollfd, STDIN_FILENO); epoll_add (epollfd, selfpiperead); struct epoll_event events[MAX_QUEUE]; int i, n; char cmd; while (1) { n = epoll_wait (epollfd, events, MAX_QUEUE, -1); for (i = 0; i < n; i++) { if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) { exit(1); } else if (STDIN_FILENO == events[i].data.fd) { // user input event cmd = getchar(); switch (cmd) { case 'k': printf ("Killing workers\n"); finish(1); break; case 'q': printf ("Telling workers to exit\n"); finish(0); break; case '+': spawn_workers (worker_count + 1); break; case '-': spawn_workers (worker_count - 1); break; } } else { // pipe event if (read (selfpiperead, &cmd, 1) <= 0) { die ("read"); } switch (cmd) { case CMD_KILL: printf ("Killing workers\n"); finish(0); break; case CMD_TERM: printf ("Telling workers to exit\n"); finish(1); break; case CMD_INCR: spawn_workers (worker_count + 1); break; case CMD_DECR: spawn_workers (worker_count - 1); break; case CMD_CHLD: check_workers(); break; } } } } return 0; }
/** * Main server event loop. */ static int child (const int8_t index, const uint8_t *server_port) { int listensock, epollfd; struct epoll_event event, *events; /* setup listen socket */ if ((listensock = setup_listener (server_port)) < 0) { err (1, "Could not setup listen socket"); } fprintf (stdout, "proc %d: Listening on port %s...\n", index, (char *) server_port); /* initialize cache */ if (cache_init ((const uint8_t *) CACHE_BASEDIR) < 0) { err (1, "Could not create cache dir"); } fprintf (stdout, "proc %d: Initialized cache...\n", index); /* initialize epoll */ if ((epollfd = epoll_create1 (0)) < 0) { err (1, "Could not initialize epoll"); } /* add epoll event for handling listen socket */ struct command *lcmd = calloc (1, sizeof (struct command)); lcmd->cfd = listensock; epoll_add (epollfd, lcmd); /* event buffer */ events = calloc (MAXEVENTS, sizeof (event)); fprintf (stdout, "proc %d: Entering main loop...\n", index); for (;;) { /* block until we get some events to process */ int numevents = epoll_wait (epollfd, events, MAXEVENTS, -1); struct command *command; /* process all events */ for (int i = 0; i < numevents; i++) { /* get command */ command = events[i].data.ptr; /* epoll error */ if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) { /* notified but nothing ready for processing */ warn ("epoll error"); close (command->cfd); close (command->rfd); continue; } /* ACCEPT */ else if (command->cfd == listensock) { do_accept (listensock, epollfd); /* processed all incoming events on listensock, continue to * next event. */ continue; } /* HANDLE COMMANDS */ else { switch (command->cmd) { case READ_CMD: do_read_cmd (epollfd, command); break; case READ_REMOTE: ; /* hack needed for variable defs inside switch */ uint8_t buf[BUFLEN] = { 0 }; ssize_t buflen; /* command is free'd in d_r_r() */ int cfd = command->cfd; do_read_remote (command, buf, &buflen); /* verify that we actually have data to relay back */ if (buflen > 0) { if (!sendall (cfd, buf, (size_t *) &buflen)) { warn ("Could not relay back data to client"); } } break; default: break; } } } } free (events); close (listensock); return EXIT_SUCCESS; }
int vfs_signalling_thread(void *arg) { t_thread_arg *argp = (t_thread_arg *)arg; if (sub_init_signalling(argp->name)) { LOG(glogfd, LOG_ERROR, "sub_init_signalling %s err %m\n", argp->name); stop = 1; return -1; } if (argp->port > 0) { lfd = get_listen_sock(argp->port); if (lfd < 0) { LOG(glogfd, LOG_ERROR, "get_listen_sock err %d\n", argp->port); stop = 1; return -1; } LOG(glogfd, LOG_DEBUG, "%s listen on %d\n", argp->name, argp->port); } maxevent = argp->maxevent; epfd = epoll_create(maxevent); if(epfd < 0) { LOG(glogfd, LOG_ERROR, "epoll_create(%d): %m\n", maxevent); stop = 1; return -1; } pev = (struct epoll_event*)malloc(sizeof(struct epoll_event) * maxevent); if(pev == NULL) { LOG(glogfd, LOG_ERROR, "allocate epoll_event(%d): %m\n", maxevent); stop = 1; return -1; } if (argp->port > 0) { if (argp->flag) set_socket_attr(lfd); } iobuf = malloc(init_buff_size); if (iobuf == NULL) { LOG(glogfd, LOG_ERROR, "allocate iobuf [%d] error %m\n", init_buff_size); stop = 1; return -1; } struct threadstat *thst = get_threadstat(); int event = EPOLLIN; if (argp->port > 0) epoll_add(epfd, lfd, event); int n = 0, i = 0; time_t last = time(NULL); time_t now = last; LOG(glogfd, LOG_DEBUG, "%s:%s:%d\n", ID, FUNC, LN); while (!stop) { n = epoll_wait(epfd, pev, maxevent, 1000); for(i = 0; i < n; i++) { if (argp->port > 0 && pev[i].data.fd == lfd) accept_new(); else do_process(pev[i].data.fd, pev[i].events); } thread_reached(thst); now = time(NULL); if (now > last + g_config.cktimeout) { last = now; if (solib.svc_timeout) solib.svc_timeout(); } } return 0; }