bool server_tick(server_t server, int timeout_ms) { int i; int numready; bool raft_ready = false; #ifdef USE_EPOLL struct epoll_event events[MAX_EVENTS]; numready = epoll_wait(server->epollfd, events, MAX_EVENTS, timeout_ms); if (numready < 0) { shout("failed to epoll: %s\n", strerror(errno)); return false; } for (i = 0; i < numready; i++) { stream_t stream = (stream_t)events[i].data.ptr; if (stream == NULL) { server_accept(server); } else if (stream == &server->raft_stream) { raft_ready = true; } else { if (events[i].events & EPOLLERR) { stream->good = false; } else if (events[i].events & EPOLLIN) { server_stream_handle(server, stream); } } } #else fd_set readfds = server->all; struct timeval timeout = ms2tv(timeout_ms); numready = select(server->maxfd + 1, &readfds, NULL, NULL, &timeout); if (numready == -1) { shout("failed to select: %s\n", strerror(errno)); return false; } if (FD_ISSET(server->listener, &readfds)) { numready--; server_accept(server); } if ((server->raft_stream.good) && FD_ISSET(server->raft_stream.fd, &readfds)) { numready--; raft_ready = true; } stream_t s; for (s = server_used_chain; (s != NULL) && (numready > 0); s = s->next) { if (FD_ISSET(s->fd, &readfds)) { server_stream_handle(server, s); numready--; } } #endif server_close_bad_streams(server); server_flush(server); return raft_ready; }
static void store_tuple_if_new (client_t *self) { server_accept (self->server, zgossip_msg_key (self->message), zgossip_msg_value (self->message)); }
void server_loop(server_t server) { while (1) { int i; fd_set readfds = server->all; debug("selecting\n"); int numready = select(server->maxfd + 1, &readfds, NULL, NULL, NULL); if (numready == -1) { shout("failed to select: %s\n", strerror(errno)); return; } if (FD_ISSET(server->listener, &readfds)) { numready--; server_accept(server); } for (i = 0; (i < server->streamsnum) && (numready > 0); i++) { stream_t stream = server->streams + i; if (FD_ISSET(stream->fd, &readfds)) { server_stream_handle(server, stream); numready--; } } server_close_bad_streams(server); server_flush(server); } }
static gboolean retry_server_accept(void *user_data) { struct input_server *server = user_data; struct btd_device *device = NULL; DBG(""); device = device_for_connection(&server->pending_accept.src, &server->pending_accept.dst); if (!device) { DBG("No device"); goto cleanup; } if (device_has_service_records(device)) { DBG("Device has service records"); if (!server_accept(server)) DBG("Accept failed"); goto cleanup; } if (server->pending_accept.retries >= MAX_ACCEPT_RETRIES) { DBG("Retry cap reached."); goto cleanup; } server->pending_accept.retries++; return TRUE; cleanup: server->pending_accept.timer = 0; g_io_channel_unref(server->pending_accept.chan); server->pending_accept.chan = NULL; return FALSE; }
static zmsg_t * server_method (server_t *self, const char *method, zmsg_t *msg) { // Connect to a remote zmsg_t *reply = NULL; if (streq (method, "CONNECT")) { char *endpoint = zmsg_popstr (msg); assert (endpoint); server_connect (self, endpoint); zstr_free (&endpoint); } else if (streq (method, "PUBLISH")) { char *key = zmsg_popstr (msg); char *value = zmsg_popstr (msg); server_accept (self, key, value); zstr_free (&key); zstr_free (&value); } else if (streq (method, "STATUS")) { // Return number of tuples we have stored reply = zmsg_new (); assert (reply); zmsg_addstr (reply, "STATUS"); zmsg_addstrf (reply, "%d", (int) zhashx_size (self->tuples)); } else zsys_error ("unknown zgossip method '%s'", method); return reply; }
int main(int argc, char* argv[]) { process_arg(argc,argv); tcpudp_fd=open_socket(); assert(tcpudp_fd>0); if(server) server_accept(NULL); tun_fd=tun_alloc(tun_name,IFF_TAP); assert(tun_fd>0); get_macaddr(); write_n(tcpudp_fd,tun_mac,6); getack(); if(pthread_create(&pt_read_from_if,NULL,read_from_if,NULL)!=0){ perror("pthread_create"); exit(-1); } if(pthread_create(&pt_read_from_sock,NULL,read_from_sock,NULL)!=0){ perror("pthread_create"); exit(-1); } printf("engin started, main() going to sleep\n"); pthread_join(pt_read_from_if,NULL); pthread_join(pt_read_from_sock,NULL); return 0; }
client_t *server_start_file_writer(const char *filename) { int fd = open(filename, O_CREAT|O_WRONLY|O_TRUNC|O_EXCL, 0644); if (fd < 0) return NULL; char address[512]; snprintf(address, sizeof(address), "special:file:%s", filename); return server_accept(fd, address); }
/** * waiting the hearbeat send by the child process * @param server_fd [description] */ void wait_heart_beat(int server_fd) { int client_fd; int nread; int tmp_fd; int flag; int rv; fd_set readfds; fd_set testfds; FD_ZERO(&readfds); FD_SET(server_fd, &readfds); while (1) { testfds = readfds; rv = select(FD_SETSIZE, &testfds, (fd_set *)NULL, (fd_set *)NULL, (struct timeval *)NULL); switch (rv) { case -1: perror("select"); break; default: for (tmp_fd = 0; tmp_fd < FD_SETSIZE; tmp_fd++) { if (FD_ISSET(tmp_fd, &testfds)) { if (tmp_fd == server_fd) { client_fd = server_accept(server_fd); printf("a client connected\n"); FD_SET(client_fd, &readfds); } else { nread = read(tmp_fd, &flag, sizeof(flag)); if (nread > 0) { printf("flag = %d\n", flag); reset(flag); } else if (nread == 0) { printf("a client disconnected\n"); FD_CLR(tmp_fd, &readfds); close(tmp_fd); } else { FD_CLR(tmp_fd, &readfds); close(tmp_fd); } } } } break; } } }
static int server(size_t paramlen) { int ret; ret = server_reject(paramlen); if (ret) return ret; return server_accept(paramlen); }
/* * Listen for incoming connections until told to stop */ int server_listen (XML *xml, NETCON *conn, NETCON *ssl, SSL_CTX *ctx, int threads) { char *ch; TASKQ *t; struct timeval timeout; fd_set fds; if ((conn == NULL) && (ssl == NULL)) return (-1); t = task_allocq (threads, 2); timeout.tv_sec = 2; timeout.tv_usec = 0; /* * Keep servicing requests until they stop coming in AND we are * no longer running. This insures a nice shutdown, although a * naughty client could keep us from shutting down by flooding us * with requests. We could add a counter here to prevent that. */ while (1) { FD_ZERO (&fds); if (conn != NULL) FD_SET (conn->sock, &fds); if (ssl != NULL) FD_SET (ssl->sock, &fds); if (select (2, &fds, NULL, NULL, &timeout) <= 0) { if (phineas_running ()) continue; break; } if ((conn != NULL) && FD_ISSET (conn->sock, &fds)) server_accept (xml, conn, NULL, t); if ((ssl != NULL) && FD_ISSET (ssl->sock, &fds)) server_accept (xml, ssl, ctx, t); } task_stop (t); task_freeq (t); return (0); }
static void ctrl_confirm_event_cb(GIOChannel *chan, gpointer user_data) { struct input_server *server = user_data; bdaddr_t src, dst; GError *err = NULL; struct btd_device *device = NULL; DBG(""); bt_io_get(chan, BT_IO_L2CAP, &err, BT_IO_OPT_SOURCE_BDADDR, &src, BT_IO_OPT_DEST_BDADDR, &dst, BT_IO_OPT_INVALID); if (err) { error("%s", err->message); g_error_free(err); goto drop; } device = device_for_connection(&src, &dst); if (!device) { DBG("No device."); goto drop; } if (device_has_service_records(device)) { DBG("Device has service records"); server->pending_accept.chan = chan; if (server_accept(server)) return; DBG("Accept failed"); goto drop; } if (server->pending_accept.timer) { DBG("Accept already pending."); goto drop; } DBG("Device has no service records, pending accept."); server->pending_accept.chan = chan; g_io_channel_ref(server->pending_accept.chan); server->pending_accept.retries = 0; server->pending_accept.src = src; server->pending_accept.dst = dst; server->pending_accept.timer = g_timeout_add_seconds(1, retry_server_accept, server); return; drop: g_io_channel_shutdown(chan, TRUE, NULL); }
/*通过poll函数循环监视套结字*/ int poll_server (int *sock_fd) { int server_recv_return = 0 ; int n ; int poll_num = 0 ; /*记录poll函数返回 发生事件的套结字的个数*/ int count = 0 ; /*需要监视的套结字个数*/ struct pollfd poll_fd[POLLMAX] ; /*监视列表数组*/ struct pollfd *poll_fd_temp ; memset (&poll_fd[0], 0, POLLMAX*sizeof (struct pollfd)) ; /*监视列表数组全部清0*/ /*将侦听套结字存入poll_fd[0]元素中,监听事件为有普通可读数据就绪*/ poll_fd[0].fd = *sock_fd ; poll_fd[0].events = POLLRDNORM ; count = 1 ; /*循环监视事件*/ while((poll_num = poll (&poll_fd[0], count, -1)) >= 0) {printf ("start deal\n") ; if(poll_fd[0].revents == POLLRDNORM) { /*侦听套结字上有可读数据时,说明有客户端请求连接*/ /*从监视列表中寻找第一个未使用的元素*/ if((poll_fd_temp = poll_get (&poll_fd[0])) == NULL) { printf ("too many client\n") ; break ; } if(server_accept (&poll_fd[0].fd, poll_fd_temp) < 0) { break ; } count++ ; } /*将整个监视列表查看一遍,对发生事件的套结字进行处理*/ for(n = 1; n < POLLMAX; n++) { if(poll_fd[n].revents == POLLRDNORM) { /*接收命令包*/ if((server_recv_return = server_recv (&poll_fd[n])) < 0) { continue ; } /*如果该套结字断开连接,将poll_fd数组中该元素清空*/ else if(server_recv_return == 1) { memset (&poll_fd[n], 0, sizeof (struct pollfd)) ; printf ("a client gone\n") ; } else { poll_fd[n].revents = 0 ; /*重新将发生的事件置为0,以便下一次监视*/ } poll_num-- ; } if(poll_num <= 0) { /*发生事件的套结字处理完,直接退出循环*/ break ; } } printf ("deal end\n") ; } return 0 ; }
/** * Accepts incoming connections * @param arg Manager structure to pass into new clients */ void *connection_thread( void *arg ) { ConnectionThreadStruct conn = (ConnectionThreadStruct)arg; while( cease != 1 ){ Client client = server_accept( conn->server ); if( client == NULL ) continue; // make the client non blocking int status = fcntl( client->socket, F_SETFL, fcntl(client->socket, F_GETFL, 0) | O_NONBLOCK // set non blocking ); // probs won't' if (status == -1){ perror("calling fcntl"); } Environment arg = new_env_arg( client, conn->manager ); pthread_t thread; // client thread int err = pthread_create( &thread, NULL, user_thread, arg); // check for error if (err != 0) { perror("Creating thread"); } client->thread = thread; } // wait for threads to clean themselves while( manager_thread_count( conn->manager ) > 0 ){ // going to wait for threads to clean themselves up sched_yield(); } // wait for the last one if( conn->manager->last_thread != 0 ){ printf("joining last thread\n"); pthread_join( conn->manager->last_thread, NULL ); } }
int main(void) { Server *server = server_new("0.0.0.0", 7000); //Server *server = server_new("::", 7000); Status rc; rc = server_listen(server, 0); insist_return(rc == GREAT_SUCCESS, rc, "Server failed to start listening") printf("fd: %d\n", server->fd); server_accept(server); return 0; } /* main */
static int _server_action(const t_server *server, fd_set *rfd, fd_set *wfd) { server_accept(server, rfd); server_players_actions(server, rfd); server_exec_actions(server); server_notify_player(server, wfd); server_graph_actions(server, rfd); server_notify_graph(server, wfd); server_deamon(server); return (EXIT_SUCCESS); }
void server() { int server_fd = start_server(SERVER_ADDRESS, SERVER_PORT); int client_fd = server_accept( server_fd ); printf("Server sleeping\n"); sleep(60); printf( "Errno before: %s\n", strerror( errno ) ); printf( "Write result: %d\n", write( client_fd, "123", 3 ) ); printf( "Errno after: %s\n", strerror( errno ) ); close( client_fd ); }
/* * This is the function for handling a _single_ request. Understand * what each of the steps in this function do, so that you can handle * _multiple_ requests. Use this function as an _example_ of the * basic functionality. As you increase the server in functionality, * you will want to probably keep all of the functions called in this * function, but define different code to use them. */ void server_single_request(int accept_fd) { int fd; /* * The server thread will always want to be doing the accept. * That main thread will want to hand off the new fd to the * new threads/processes/thread pool. */ fd = server_accept(accept_fd); client_process(fd); return; }
void server_write (const uint8_t *buffer, size_t size) { unsigned sock; client_t client; server_accept(); for (sock = 0; sock < MAX_SOCK_NUM; sock++) { client_init_sock (&client, sock); if (_socket_port[sock] == _server_port && client_status (&client) == SnSR_ESTABLISHED) { client_write (&client, buffer, size); } } }
int main(void) { pthread_t worker; pthread_attr_t attrt; pthread_attr_init(&attrt); pthread_attr_setdetachstate(&attrt,PTHREAD_CREATE_DETACHED); int sockfd,sockcnfd; FILE *sockfp; struct sockaddr_in clsockaddr; sockfd=make_server_socket(SERVER_PORT,SERVER_LISNUM); while(1){ sockcnfd=server_accept(sockfd,&clsockaddr); pthread_create(&worker,&attrt,process_accept,&sockcnfd); } return 0; }
void server_task_queue(int accept_fd) { //5! Work here! int i; pthread_t *threads = malloc(sizeof(pthread_t) * MAX_CONCURRENCY); for (i = 0 ; i < MAX_CONCURRENCY ; i++) pthread_create(&threads[i], NULL, (void *)&pthread_handle, NULL); printf("ALL THREADS CREATED\n"); for(;;) { int fd = server_accept(accept_fd); put_request(req_create((void*)fd)); printf("ADDING STUFF!\n"); } return; }
int main(int argc, char * argv[]) { int sockfd; int newsockfd; int rcvbuf = BUFSIZE; int reuseaddr = 1; long long t = 0; SIMPLEOT_SENDER sender; // if (argc != 2) { fprintf(stderr, "usage %s port\n", argv[0]); exit(-1); } // sockfd = server_listen(atoi(argv[1])); newsockfd = server_accept(sockfd); if (setsockopt(newsockfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) != 0) { perror("ERROR setsockopt"); exit(-1); } if (setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)) != 0) { perror("ERROR setsockopt"); exit(-1); } t -= cpucycles_amd64cpuinfo(); ot_sender_test(&sender, newsockfd); t += cpucycles_amd64cpuinfo(); // if (!VERBOSE) printf("[n=%d] Elapsed time: %lld cycles\n", NOTS, t); shutdown (newsockfd, 2); shutdown (sockfd, 2); // return 0; }
void server_processes(int accept_fd) { pid_t childID; int fd, status, endID, i; int count = 0; int temp = 0; pid_t *connect = malloc(sizeof(pid_t)*MAX_CONCURRENCY); for(;;){ while (count >= MAX_CONCURRENCY) { wait(&status); int tempCount = count; count = 0; for (i = 0 ; i < tempCount ; i++) { if (waitpid(connect[i], &status, WNOHANG|WUNTRACED)) { connect[temp] = connect[i]; temp++; } else count++; } } if (count >= MAX_CONCURRENCY) continue; else { fd = server_accept(accept_fd); if (childID == -1) { perror("FORK ERROR"); break; } else if (childID == 0) { client_process(fd); break; } else { childID = fork(); temp++; connect[temp] = childID; count++; } } } return; }
void* master_thread_routine(int *accept_fd) { int fd; while(1) { fd = server_accept(*accept_fd); if(fd != -1) { pthread_mutex_lock(&mutex); job_add(fd); pthread_mutex_unlock(&mutex); printf("master: added a job\n"); pthread_cond_signal(&cond); printf("master: signaled others\n"); } } return NULL; }
/* * This is the function for handling a _single_ request. Understand * what each of the steps in this function do, so that you can handle * _multiple_ requests. Use this function as an _example_ of the * basic functionality. As you increase the server in functionality, * you will want to probably keep all of the functions called in this * function, but define different code to use them. */ void server_single_request(int accept_fd) { int fd; /* * The server thread will always want to be doing the accept. * That main thread will want to hand off the new fd to the * new threads/processes/thread pool. */ fd = server_accept(accept_fd); client_process(fd); /* * A loop around these two lines will result in multiple * documents being served. */ return; }
void server_thread_per(int accept_fd) { // 4! Work here! pthread_t *threadArray = malloc(sizeof(pthread_t) * MAX_CONCURRENCY); int fd, i, count = 0; for(;;) { if (count < MAX_CONCURRENCY) { fd = server_accept(accept_fd); if (!pthread_create(&threadArray[count], NULL, (void*)&client_process, (void*) fd)) count++; } else for (i = 0; i < MAX_CONCURRENCY ; i++) if (!pthread_join(threadArray[i], NULL)) count--; } return; }
int server_available (client_t *client) { unsigned sock; server_accept(); for (sock = 0; sock < MAX_SOCK_NUM; sock++) { client_init_sock (client, sock); if (_socket_port[sock] == _server_port && (client_status (client) == SnSR_ESTABLISHED || client_status (client) == SnSR_CLOSE_WAIT)) { if (client_available (client)) { // XXX: don't always pick the lowest numbered socket. return 1; } } } return 0; }
static int remote_handler (zloop_t *loop, zsock_t *remote, void *argument) { zgossip_msg_t *msg = zgossip_msg_recv (remote); if (!msg) return -1; // Interrupted if (zgossip_msg_id (msg) == ZGOSSIP_MSG_PUBLISH) server_accept ((server_t *) argument, zgossip_msg_key (msg), zgossip_msg_value (msg)); else if (zgossip_msg_id (msg) == ZGOSSIP_MSG_INVALID) // Connection was reset, so send HELLO again zgossip_msg_send_hello (remote); else if (zgossip_msg_id (msg) == ZGOSSIP_MSG_PONG) assert (true); // Do nothing with PONGs zgossip_msg_destroy (&msg); return 0; }
int main(int argc, char *argv[]){ int fd,clientfd ,size,n; char buf[1024]; struct sockaddr_un un; memset(&un,0,sizeof(un)); un.sun_family=AF_UNIX; strcpy(un.sun_path,"/tmp/my_unix_socket"); unlink(un.sun_path); /* delete already exits "/tmp/my_unix_socket" */ fd=socket(AF_UNIX,SOCK_STREAM,0); if(fd<0){ perror("socket error"); exit(1); } size=offsetof(struct sockaddr_un,sun_path)+strlen(un.sun_path); /* offsetof宏,用来取成员在结构体中的偏移量 offsetof(struct sockaddr_un, sun_path)就是取 sockaddr_un结构体的sun_path成员在结构体中的偏移 */ if (-1==bind(fd,(struct sockaddr*)&un,size)){ perror("bind unix socket error"); exit(1); } printf ("unix socket binded\n"); if(-1==listen(fd, QUEUE_LEN)){ perror("listen error"); exit(1); } clientfd = server_accept(fd,NULL); if(clientfd<0)exit(1); n=read(clientfd,buf,1024); if(n>0){ write(STDOUT_FILENO,buf,n); write(clientfd,buf,n); } else exit(-1); return 0; }
static int remote_handler (zloop_t *loop, zsock_t *remote, void *argument) { server_t *self = (server_t *) argument; if (zgossip_msg_recv (self->message, remote)) return -1; // Interrupted if (zgossip_msg_id (self->message) == ZGOSSIP_MSG_PUBLISH) server_accept (self, zgossip_msg_key (self->message), zgossip_msg_value (self->message)); else if (zgossip_msg_id (self->message) == ZGOSSIP_MSG_INVALID) { // Connection was reset, so send HELLO again zgossip_msg_set_id (self->message, ZGOSSIP_MSG_HELLO); zgossip_msg_send (self->message, remote); } else if (zgossip_msg_id (self->message) == ZGOSSIP_MSG_PONG) assert (true); // Do nothing with PONGs return 0; }
void server_run (server_t * s, const char * port) { int i; server_bind(s, port); server_listen(s); // Clear the master and temp sets FD_ZERO(&(s->master)); FD_ZERO(&(s->read_fds)); // Add the listener to the master set FD_SET(s->listener, &(s->master)); // Keep track of the biggest file descriptor s->fdmax = s->listener; // so far, it's this one while (1) { s->read_fds = s->master; if (select(s->fdmax + 1, &(s->read_fds), NULL, NULL, NULL) == -1) { exit(1); } for (i = 0; i <= s->fdmax; i ++) { if (FD_ISSET(i, &(s->read_fds))) { if (i == s->listener) { // Handle new connection server_accept(s); } else { // Handle data from a client robot_recv(s->robots[i]); } } } } }