server_t* parse_nameserver(const char *nameserver, const char *def_port) { if (nameserver == NULL || def_port == NULL) { DBG_NULL; return NULL; } // OpenBSD notation: nameserver [address]:port if (nameserver[0] == '[') { char *addr, *port; char *start = (char *)nameserver + 1; char *end = index(nameserver, ']'); size_t addr_len = end - start; // Missing closing bracket -> stop processing. if (end == NULL) { return NULL; } // Fill enclosed address. addr = strndup(start, addr_len); // Find possible port. start += addr_len + 1; if (strlen(start) > 0) { // Check for colon separation. if (*start != ':') { free(addr); return NULL; } size_t port_len = strlen(++start); // Check port string length. if (port_len == 0 || port_len >= sizeof(port)) { free(addr); return NULL; } // Fill port part. port = strdup(start); } else { port = strdup(def_port); } // Create server structure. server_t *server = server_create(addr, port); free(addr); free(port); return server; } else { return server_create(nameserver, def_port); } }
int main(int argc, char const* argv[]) { server_t* s; sigset_t mask; siginfo_t info; struct sigaction action; if(argc == 1) { if(!server_create(&s, "../calories.csv", NULL)) { if(!server_create(&s, "./calories.csv", NULL)) { printf("File '%s' fot found\n", "calories.csv"); exit(1); } } } else if(argc == 2) { if(!server_create(&s, "../calories.csv", argv[1])) { if(!server_create(&s, "./calories.csv", argv[1])) { printf("File '%s' fot found\n", "calories.csv"); exit(1); } } } else { printf("%s\n", SERVER_MAIN_HELP); exit(1); } printf("Press CTRL+C to shutdown the server\n"); sigemptyset(&mask); sigaddset(&mask, SIGINT); sigprocmask(SIG_BLOCK, &mask, NULL); sigemptyset(&action.sa_mask); action.sa_flags = SA_SIGINFO; sigaction(SIGCHLD, &action, NULL); if(server_start(s)) { while(true) { // signal() is NOT thread safe! // And since the server doesn't block signal handling is "not" needed ... if(sigwaitinfo(&mask, &info) == -1) { perror("sigwaitinfo() failed"); exit(1); } switch(info.si_signo) { case SIGINT: server_destroy(s); return 0; } } } else { server_destroy(s); } }
static struct connection *conn_create_server(struct context *ctx, struct address *addr, char *key, bool readonly) { int fd = conn_create_fd(); if (fd == -1) { LOG(ERROR, "conn_create_server: fail to create fd"); return NULL; } struct connection *server = server_create(ctx, fd); struct conn_info *info = server->info; memcpy(&info->addr, addr, sizeof(info->addr)); extern const size_t CMD_NUM; info->slow_cmd_counts = cv_calloc(CMD_NUM, sizeof(uint32_t)); if (conn_connect(server) == CORVUS_ERR) { LOG(ERROR, "conn_create_server: fail to connect %s:%d", info->addr.ip, info->addr.port); conn_free(server); conn_buf_free(server); conn_recycle(ctx, server); return NULL; } if (readonly) { server->info->readonly = true; } strncpy(info->dsn, key, ADDRESS_LEN); dict_set(&ctx->server_table, info->dsn, (void*)server); TAILQ_INSERT_TAIL(&ctx->servers, server, next); return server; }
int nzb_fetch_add_server(nzb_fetch *fetcher, char *address, int port, char *username, char *password, int threads, int ssl, int priority) { server_t *new_server, *server; int required_queues; int current_queues; if (priority < 0) { fprintf(stderr, "Error: priority should be > 0\n"); return -1; } #if !HAVE_LIBSSL if (ssl > 0) { fprintf(stderr, "Error: SSL Support is not compiled in\n"); return -1; } #endif new_server = server_create(address, port, username, password, threads, ssl, priority); // Insert into server linked list server = fetcher->servers; if(server == NULL) fetcher->servers = new_server; else { // Append server at the end while(server->next != NULL) server = server->next; server->next = new_server; new_server->prev = server; } required_queues = server_calc_priorities(fetcher); if (required_queues > 1) { current_queues = sizeof(fetcher->priority_queues) / sizeof(queue_list_t *); if (required_queues > current_queues) { fetcher->priority_queues = reallocf(fetcher->priority_queues, sizeof(queue_list_t *) * required_queues); fetcher->priority_queues[new_server->priority] = queue_list_create(); fetcher->priority_queues[new_server->priority]->id = strdup("priority queue"); } } return 0; }
int main(int argc, const char *argv[]) { if (argc != 3) { print_usage(); return 1; } setup_signal_handlers(); server *s = server_create((uint16_t)atoi(argv[1]), argv[2]); server_listen(s); printf("Listening...\n"); fflush(stdout); while (running) { server_wait(s); } printf("Shutting down...\n"); fflush(stdout); server_close(s); server_destroy(s); return 0; }
static struct connection *conn_create_server(struct context *ctx, struct address *addr, char *key) { int fd = conn_create_fd(); if (fd == -1) { LOG(ERROR, "conn_create_server: fail to create fd"); return NULL; } struct connection *server = server_create(ctx, fd); struct conn_info *info = server->info; memcpy(&info->addr, addr, sizeof(info->addr)); if (conn_connect(server) == CORVUS_ERR) { LOG(ERROR, "conn_create_server: fail to connect %s:%d", info->addr.ip, info->addr.port); conn_free(server); conn_buf_free(server); conn_recycle(ctx, server); return NULL; } strncpy(info->dsn, key, DSN_LEN); dict_set(&ctx->server_table, info->dsn, (void*)server); TAILQ_INSERT_TAIL(&ctx->servers, server, next); return server; }
int main() { //init win32 socket #ifdef __WIN32__ static WSADATA wsa_data; int result = WSAStartup((WORD)(1<<8|1), &wsa_data); //初始化WinSocket动态连接库 if( result != 0 ) // 初始化失败 return -1; #endif #ifndef __WIN32__ signal( SIGPIPE, SIG_IGN ); //ignore send,recv SIGPIPE error #endif NEW( websrv, sizeof(webserver) ); memset( websrv, 0, sizeof(webserver) ); server_create( websrv, "config.xml" ); server_start( websrv ); do_console(); server_stop( websrv ); server_end( websrv ); DEL( websrv ); #ifdef __WIN32__ WSACleanup(); #endif memory_end(); return 0; }
void client_init(int taskid, int num_tasks) { ASSERT(max_ep > 0); /* Create data structure to track all clients */ MALLOC_ALIGN(client_table, sizeof(client_t) * max_ep, CACHELINE_SIZE); PMPI_Barrier(MPI_COMM_WORLD); /* Initialize command queues */ cqueue_init(max_ep); /* Spawn server */ server_create(); /* Create client data-structure */ for (int clientid = 0; clientid < max_ep; clientid++) { client_t* myclient = &client_table[clientid]; myclient->clientid = clientid; myclient->taskid = taskid; /* Attach client to a command queue */ myclient->cqueue = cqueue_attach(clientid); memory_set_cqueue(clientid, myclient->cqueue); } PMPI_Barrier(MPI_COMM_WORLD); if (use_mem_hooks) set_mem_hooks = 1; }
int main(int argc, char **argv) { const uint16_t acceptor_port = (uint16_t)((argc >= 2) ? atoi(argv[1]) : 8080); char const * const settings_file_name = ((argc >= 3) ? argv[2] : "settings.txt"); settings_t settings; server_t server; log_t log; log_create(&log, stderr); if (!load_settings(&settings, settings_file_name, &log)) { return 1; } if (!server_create(&server, &log, &settings, acceptor_port)) { settings_destroy(&settings); return 1; } settings_destroy(&settings); server_run(&server); server_destroy(&server); log_destroy(&log); return 0; }
static void * lua_server(void * arg) { pthread_detach( pthread_self() ); server_create((luaServer_t *)arg); return NULL; }
int main() { struct Server *s = malloc(sizeof(struct Server)); server_create(s, "/tmp/accounts.txt", "/tmp/requests"); //server_createAccount(s, 1231, "vascoFG", "bino", 0); /*server_createAccount(s, 1234, "vascoFG", "bino", 0); server_createAccount(s, 4321, "vascoFG", "bino", 0);*/ server_run(s); return 0; }
int main(int argc, char *argv[]) { server_type_t server_type; short int port; int accept_fd; if (argc != 3) { printf("Proper usage of http server is:\n%s <port> <#>\n" "port is the port to serve on, # is either\n" "0: serve only a single request\n" "1: use only a single thread for multiple requests\n" "2: use fork to create a process for each request\n" "3: Extra Credit: use fork and exec when the path is an executable to run the program dynamically. This is how web servers handle dynamic (program generated) content.\n" "4: create a thread for each request\n" "5: use atomic instructions to implement a task queue\n" "6: use a thread pool\n" "7: to be defined\n" "8: to be defined\n" "9: to be defined\n", argv[0]); return -1; } port = atoi(argv[1]); accept_fd = server_create(port); if (accept_fd < 0) return -1; server_type = atoi(argv[2]); switch(server_type) { case SERVER_TYPE_ONE: server_single_request(accept_fd); break; case SERVER_TYPE_SINGLET: server_multiple_requests(accept_fd); break; case SERVER_TYPE_PROCESS: server_processes(accept_fd); break; case SERVER_TYPE_FORK_EXEC: server_dynamic(accept_fd); break; case SERVER_TYPE_SPAWN_THREAD: server_thread_per(accept_fd); break; case SERVER_TYPE_TASK_QUEUE: server_task_queue(accept_fd); break; case SERVER_TYPE_THREAD_POOL: server_thread_pool(accept_fd); break; } close(accept_fd); return 0; }
int nfs41_server_find_or_create( IN const char *server_owner_major_id, IN const char *server_scope, IN const netaddr4 *addr, OUT nfs41_server **server_out) { struct server_info info; struct list_entry *entry; nfs41_server *server; int status; info.owner = server_owner_major_id; info.scope = server_scope; dprintf(SRVLVL, "--> nfs41_server_find_or_create(%s)\n", info.owner); EnterCriticalSection(&g_server_list.lock); /* search for an existing server */ entry = list_search(&g_server_list.head, &info, server_compare); if (entry == NULL) { /* create a new server */ status = server_create(&info, &server); if (status == NO_ERROR) { /* add it to the list */ list_add_tail(&g_server_list.head, &server->entry); *server_out = server; dprintf(SRVLVL, "<-- nfs41_server_find_or_create() " "returning new server %p\n", server); } else { dprintf(SRVLVL, "<-- nfs41_server_find_or_create() " "returning %d\n", status); } } else { server = server_entry(entry); status = NO_ERROR; dprintf(SRVLVL, "<-- nfs41_server_find_or_create() " "returning existing server %p\n", server); } if (server) { /* register the address used to connect */ server_addrs_add(&server->addrs, addr); server_ref_locked(server); } *server_out = server; LeaveCriticalSection(&g_server_list.lock); return status; }
int get_nameservers(list *servers, const char *def_port) { if (servers == NULL || def_port == NULL) { DBG_NULL; return KNOT_EINVAL; } // Initialize list of servers. init_list(servers); // Read nameservers from resolv file. int ret = get_resolv_nameservers(servers, def_port); // If found nameservers or error. if (ret != 0) { return ret; // If no nameservers. } else { server_t *server; // Add default ipv6 nameservers. server = server_create(DEFAULT_IPV6_NAME, def_port); if (server != NULL) { add_tail(servers, (node *)server); } // Add default ipv4 nameservers. server = server_create(DEFAULT_IPV4_NAME, def_port); if (server != NULL) { add_tail(servers, (node *)server); } return list_size(servers); } }
void test_server() { socket_t serverfd = server_create("127.0.0.1", SERVER_PORT); setnonblocking(serverfd); server_listen(serverfd); event_manager_t event_manager; event_manager_init(&event_manager, serverfd, my_event_callback); event_dispatch(&event_manager); event_magager_destroy(&event_manager); }
static int run(char *default_user_path, int port) { if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) return (dprintf(2, ERR_SET_SIGNAL), 0); g_config.port = port; g_config.sock_fd = -1; g_config.client_sock_fd = -1; g_config.parent_pid = getpid(); if ((g_config.sock_fd = server_create(INADDR_ANY, port, 1)) == -1) return (dprintf(2, ERR_SERVER_CREATE, g_config.port), 0); if (user_change_home("anonymous", default_user_path) == 0) return (dprintf(2, ERR_USER_CHANGE_DIR), 0); server_run(); close(g_config.sock_fd); return (1); }
int main(int argc, char** argv) { server_t* server = server_create("config.xml"); if(server == NULL) return 0; char buf[512] = {0}; for(;;) { //sleep(1); fgets(buf, 512, stdin); if(strncmp(buf, "quit", strlen("quit")) == 0) break; } server_destroy(server); return 0; }
int main(int argc, char *argv[]) { server_type_t server_type; short int port; int accept_fd; if (argc != 3) { printf("Proper usage of http server is:\n%s <port> <#>\n" "port is the port to serve on, # is either\n" "0: server only a single request\n" "1: use a thread pool and a _bounded_ buffer with " "mutexes + condition variables\n" "2: use a thread pool and compare and swap to " "implement a lock-free stack of requests\n", argv[0]); return -1; } port = atoi(argv[1]); accept_fd = server_create(port); if (accept_fd < 0) return -1; server_type = atoi(argv[2]); switch(server_type) { case SERVER_TYPE_ONE: server_single_request(accept_fd); break; case SERVER_TYPE_THREAD_POOL_BOUND: server_thread_pool_bounded(accept_fd); break; case SERVER_TYPE_THREAD_POOL_ATOMIC: server_thread_pool_lock_free(accept_fd); break; } close(accept_fd); return 0; }
void interprocess::listen() { server_create(); char* buff; int size; while (true) { bool connected = ConnectNamedPipe(pipe_handle, NULL); if (!connected) { int error = GetLastError(); if (error != ERROR_PIPE_CONNECTED) { cout<<error<<endl; throw ipc::fifo_open_error(); } } DWORD num_bytes_read; ReadFile(pipe_handle,(char*)(&size), sizeof(size), &num_bytes_read,NULL); if (num_bytes_read == sizeof(size)) { buff = new char[size+1]; ReadFile(pipe_handle, buff, size, &num_bytes_read, NULL); if (num_bytes_read != size) { delete[] buff; throw ipc::wrong_msg_size(); } buff[size] = '\0'; last_msg = std::string(buff); cout<<"received: "<<last_msg<<endl; delete[] buff; th = std::thread(&interprocess::on_msg_receive, this, std::ref(last_msg)); th.detach(); if(last_msg == "quit") break; } } }
int main(int argc, char *argv[]) { int c; opterr = 0; while((c = getopt(argc, argv, "p:t:")) != -1) { switch(c) { case 'p': port_num = atoi(optarg); break; case't': num_threads = atoi(optarg); break; case '?': if(optopt == 'p' || optopt == 't') printf("Option -%c requires an argument\n", optopt); else printf("Unknown option -%c\n", optopt); default: printf("Usage: %s [-p port_num] [-t num_threads]\n", argv[0]); return 0; } } if(port_num < 1) { printf("Invalid port number\n"); return 0; } if(num_threads < 1) { printf("Invalid number of threads\n"); return 0; } server_create(); return 0; }
void run(void) { server_t *server; char line[4096]; int n_wait = 0; server = server_create(m_port); while (m_semaphore.wait(n_wait) != 0) { if (server_readline(server, line, sizeof(line)) == 0) { int len; len = strcspn(line, "\n\r"); if (len == 0) continue; line[len] = 0; addImage(m_gui, line, false); n_wait = 0; } else { n_wait = 10; } } server_destroy(server); }
int main(int argc, char *argv[]) { server_type_t server_type; short int port; int accept_fd; if (argc != 3) { printf("Proper usage of http server is:\n%s <port> <#>\n" "port is the port to serve on, # is either\n" "0: serve only a single request\n" "1: serve each request with kthds\n", argv[0]); return -1; } port = atoi(argv[1]); accept_fd = server_create(port); if (accept_fd < 0) return -1; server_type = atoi(argv[2]); switch(server_type) { case SERVER_TYPE_ONE: server_single_request(accept_fd); break; case SERVER_TYPE_TWO: process_kthd_server(accept_fd); break; default: perror("Unknown server type provided.\n"); } close(accept_fd); return 0; }
/** Create a http site object. * * The function nth_site_create() allocates and initializes a web site * object. A web site object can be either * - a primary http server (@a parent is NULL), * - a virtual http server (@a address contains hostpart), or * - a site within a server * (@a address does not have hostpart, only path part). * * @param parent pointer to parent site * (NULL when creating a primary server object) * @param callback pointer to callback function called when * a request is received * @param magic application context included in callback parameters * @param address absolute or relative URI specifying the address of * site * @param tag, value, ... list of tagged parameters * * @TAGS * If the @a parent is NULL, the list of tagged parameters must contain * NTHTAG_ROOT() used to create the server engine. Tags supported when @a * parent is NULL are NTHTAG_ROOT(), NTHTAG_MCLASS(), TPTAG_REUSE(), * HTTPTAG_SERVER(), and HTTPTAG_SERVER_STR(). All the tags are passed to * tport_tcreate() and tport_tbind(), too. * * @since Support for multiple sites was added to @VERSION_1_12_4 */ nth_site_t *nth_site_create(nth_site_t *parent, nth_request_f *callback, nth_site_magic_t *magic, url_string_t const *address, tag_type_t tag, tag_value_t value, ...) { nth_site_t *site = NULL, **prev = NULL; su_home_t home[SU_HOME_AUTO_SIZE(256)]; url_t *url, url0[1]; server_t *srv = NULL; ta_list ta; char *path = NULL; size_t usize; int is_host, is_path, wildcard = 0; su_home_auto(home, sizeof home); if (parent && url_is_string(address)) { char const *s = (char const *)address; size_t sep = strcspn(s, "/:"); if (parent->site_path) { /* subpath */ url_init(url0, (enum url_type_e)parent->site_url->url_type); url0->url_path = s; address = (url_string_t*)url0; } else if (s[sep] == ':') /* absolute URL with scheme */; else if (s[sep] == '\0' && strchr(s, '.') && host_is_valid(s)) { /* looks like a domain name */; url_init(url0, (enum url_type_e)parent->site_url->url_type); url0->url_host = s; address = (url_string_t*)url0; } else { /* looks like a path */ url_init(url0, (enum url_type_e)parent->site_url->url_type); url0->url_path = s; address = (url_string_t*)url0; } } url = url_hdup(home, address->us_url); if (!url || !callback) return NULL; is_host = url->url_host != NULL; is_path = url->url_path != NULL; if (is_host && is_path) { SU_DEBUG_3(("nth_site_create(): virtual host and path simultanously\n")); errno = EINVAL; goto error; } if (!parent && !is_host) { SU_DEBUG_3(("nth_site_create(): host is required\n")); errno = EINVAL; goto error; } if (parent) { if (!parent->site_isdir) { SU_DEBUG_3(("nth_site_create(): invalid parent resource \n")); errno = EINVAL; goto error; } srv = parent->site_server; assert(srv); if (is_host) { prev = site_get_host(&srv->srv_sites, url->url_host, url->url_port); if (prev == NULL) { SU_DEBUG_3(("nth_site_create(): host %s:%s already exists\n", url->url_host, url->url_port ? url->url_port : "")); errno = EEXIST; goto error; } } else { size_t i, j; path = (char *)url->url_path; while (path[0] == '/') path++; /* Remove duplicate // */ for (i = j = 0; path[i];) { while (path[i] == '/' && path[i + 1] == '/') i++; path[j++] = path[i++]; } path[j] = path[i]; url = url0, *url = *parent->site_url; if (url->url_path) { url->url_path = su_strcat(home, url->url_path, path); if (!url->url_path) goto error; path = (char *)url->url_path + strlen(parent->site_url->url_path); } else url->url_path = path; prev = site_get_rslot(parent, path, &path); if (!prev || path[0] == '\0') { SU_DEBUG_3(("nth_site_create(): directory \"%s\" already exists\n", url->url_path)); errno = EEXIST; goto error; } } } if (!parent) { if (strcmp(url->url_host, "*") == 0 || host_cmp(url->url_host, "0.0.0.0") == 0 || host_cmp(url->url_host, "::") == 0) wildcard = 1, url->url_host = "*"; } usize = sizeof(*url) + url_xtra(url); ta_start(ta, tag, value); if (!parent) { srv = server_create(url, ta_tags(ta)); prev = &srv->srv_sites; } if (srv && (site = su_zalloc(srv->srv_home, (sizeof *site) + usize))) { site->site_url = (url_t *)(site + 1); url_dup((void *)(site->site_url + 1), usize - sizeof(*url), site->site_url, url); assert(prev); if ((site->site_next = *prev)) site->site_next->site_prev = &site->site_next; *prev = site, site->site_prev = prev; site->site_server = srv; if (path) { size_t path_len; site->site_path = site->site_url->url_path + (path - url->url_path); path_len = strlen(site->site_path); assert(path_len > 0); if (path_len > 0 && site->site_path[path_len - 1] == '/') path_len--, site->site_isdir = 1; site->site_path_len = path_len; } else { site->site_isdir = is_host; site->site_path = ""; site->site_path_len = 0; } site->site_wildcard = wildcard; site->site_callback = callback; site->site_magic = magic; if (parent) site->site_auth = parent->site_auth; nth_site_set_params(site, ta_tags(ta)); } ta_end(ta); error: su_home_deinit(home); return site; }
int main(int argc, char **args) { pthread_t stats_thrd; uint8_t addrs_len; ipv4_t *addrs; uint32_t total = 0; struct telnet_info info; #ifdef DEBUG addrs_len = 1; addrs = calloc(4, sizeof (ipv4_t)); addrs[0] = inet_addr("0.0.0.0"); #else addrs_len = 2; addrs = calloc(addrs_len, sizeof (ipv4_t)); addrs[0] = inet_addr("192.168.0.1"); // Address to bind to addrs[1] = inet_addr("192.168.1.1"); // Address to bind to #endif if (argc == 2) { id_tag = args[1]; } if (!binary_init()) { printf("Failed to load bins/dlr.* as dropper\n"); return 1; } /* wget address tftp address */ if ((srv = server_create(sysconf(_SC_NPROCESSORS_ONLN), addrs_len, addrs, 1024 * 64, "100.200.100.100", 80, "100.200.100.100")) == NULL) { printf("Failed to initialize server. Aborting\n"); return 1; } pthread_create(&stats_thrd, NULL, stats_thread, NULL); // Read from stdin while (TRUE) { char strbuf[1024]; if (fgets(strbuf, sizeof (strbuf), stdin) == NULL) break; util_trim(strbuf); if (strlen(strbuf) == 0) { usleep(10000); continue; } memset(&info, 0, sizeof(struct telnet_info)); if (telnet_info_parse(strbuf, &info) == NULL) printf("Failed to parse telnet info: \"%s\" Format -> ip:port user:pass arch\n", strbuf); else { if (srv == NULL) printf("srv == NULL 2\n"); server_queue_telnet(srv, &info); if (total++ % 1000 == 0) sleep(1); } ATOMIC_INC(&srv->total_input); } printf("Hit end of input.\n"); while(ATOMIC_GET(&srv->curr_open) > 0) sleep(1); return 0; }
int main(int argc, char **argv) { // for (int i=1; i<NSIG; i++) { // //if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); // if (signal(i, sig_handler) == SIG_ERR) printf("\ncan't catch %s\n", strsignal(i)); // } signal(SIGPIPE, SIG_IGN); apr_initialize(); apr_pool_create(&mp_rpc_, NULL); apr_thread_cond_create(&cd_rpc_, mp_rpc_); apr_thread_mutex_create(&mx_rpc_, APR_THREAD_MUTEX_UNNESTED, mp_rpc_); rpc_init(); arg_parse(argc, argv); ADD = is_fast_ ? FAST_ADD : SLOW_ADD; bool exit = false; exit |= !(is_server_ || is_client_); exit |= (addr_ == NULL); exit |= (port_ == 0); if (exit) { fprintf(stderr, "wrong arguments.\n"); usage(argv[0]); return 0; } if (is_server_) { server_t *server = NULL; poll_mgr_t *mgr_server = NULL; poll_mgr_create(&mgr_server, n_server_thread_); server_create(&server, mgr_server); strcpy(server->comm->ip, addr_); server->comm->port = port_; server_reg(server, ADD, add); server_start(server); LOG_INFO("server started start on %s, port %d.", addr_, port_); } if (is_client_) { LOG_INFO("client to %s:%d, test for %d rpc in total, outstanding rpc: %d", addr_, port_, max_rpc_, max_outst_); mgrs_ = (poll_mgr_t **) malloc(n_client_ * sizeof(poll_mgr_t*)); clis_ = (client_t **) malloc(n_client_ * sizeof(client_t *)); n_issues_ = (uint64_t*) malloc(n_client_ * sizeof(uint64_t)); n_callbacks_ = (uint64_t*) malloc(n_client_ * sizeof(uint64_t)); n_active_cli_ = n_client_; apr_thread_mutex_lock(mx_rpc_); for (int i = 0; i < n_client_; i++) { apr_thread_t *th; apr_thread_create(&th, NULL, client_thread, (intptr_t) i, mp_rpc_); } if (max_rpc_ < 0) { LOG_INFO("infinite rpc on %d threads (clients)", n_client_); } else { LOG_INFO("%d threads (clients), each client run for %d rpc.", n_client_, max_rpc_ * n_client_); } apr_thread_cond_wait(cd_rpc_, mx_rpc_); apr_thread_mutex_unlock(mx_rpc_); int period = (tm_end_ - tm_begin_); //micro seconds LOG_INFO("finish %d rpc in %d ms.", max_rpc_ * n_client_, period/1000); float rate = (float) max_rpc_ * n_client_ / period; LOG_INFO("rpc rate %f million per sec.", rate); for (int i = 0; i < n_client_; i++) { client_destroy(clis_[i]); poll_mgr_destroy(mgrs_[i]); } free (clis_); free (n_issues_); } fflush(stdout); fflush(stderr); while(is_server_) { apr_sleep(1000000); } rpc_destroy(); atexit(apr_terminate); }
int main(int argc, char **argv) { // for (int i=1; i<NSIG; i++) { // //if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); // if (signal(i, sig_handler) == SIG_ERR) printf("\ncan't catch %s\n", strsignal(i)); // } signal(SIGPIPE, SIG_IGN); apr_initialize(); apr_pool_create(&mp_rpc_, NULL); apr_thread_cond_create(&cd_rpc_, mp_rpc_); apr_thread_mutex_create(&mx_rpc_, APR_THREAD_MUTEX_UNNESTED, mp_rpc_); rpc_init(); arg_parse(argc, argv); bool exit = false; exit |= !(is_server_ || is_client_); exit |= (addr_ == NULL); exit |= (port_ == 0); if (exit) { fprintf(stderr, "wrong arguments.\n"); usage(argv[0]); return 0; } if (is_server_) { server_t *server = NULL; server_create(&server, NULL); strcpy(server->comm->ip, addr_); server->comm->port = port_; server_reg(server, ADD, add); server_start(server); LOG_INFO("server started start on %s, port %d.", addr_, port_); } if (is_client_) { LOG_INFO("client to %s:%d, test for %d rpc in total, outstanding rpc: %d", addr_, port_, max_rpc_, max_outst_); apr_thread_mutex_lock(mx_rpc_); for (int i = 0; i < n_client_; i++) { apr_thread_t *th; apr_thread_create(&th, NULL, client_thread, NULL, mp_rpc_); } LOG_INFO("rpc triggered for %d adds on %d threads.", max_rpc_ * n_client_, n_client_); apr_thread_cond_wait(cd_rpc_, mx_rpc_); apr_thread_mutex_unlock(mx_rpc_); int period = (tm_end_ - tm_begin_); //micro seconds LOG_INFO("finish %d rpc in %d ms.", max_rpc_ * n_client_, period/1000); float rate = (float) max_rpc_ * n_client_ / period; LOG_INFO("rpc rate %f million per sec.", rate); } fflush(stdout); fflush(stderr); while(is_server_) { apr_sleep(1000000); } rpc_destroy(); atexit(apr_terminate); }
int main(int argc, char **argv) { int conf_err = 0; int option; int dflag = 0; conf_ruleset_s rset; // Set the default logger to syslog log_syslog(&logger); // Initialize the config and its rulesets conf_init(&conf); conf_rset_init(&rset); // Set the real path conf_set_realpath(&conf, argv[0]); conf_rset_add(&rset, conf_rule_create("root = %s", &conf.document_root)); conf_rset_add(&rset, conf_rule_create("handler = %s", &conf.method)); conf_rset_add(&rset, conf_rule_create("port = %hu", &conf.port)); conf_rset_add(&rset, conf_rule_create("backlog = %d", &conf.backlog)); conf_rset_add(&rset, conf_rule_create("mime = %s", &conf.mime)); conf_rset_add(&rset, conf_rule_create("logfile = %s", &conf.logfile)); if (conf_read(conf.real_path, ".lab3-config", rset) == -1) exit_fatal("The configuration file could not be read"); while((option = getopt(argc, argv, "hp:dl:s:")) != -1) { switch(option) { case 'p': conf_set_port(&conf, optarg); break; case 'd': dflag = 1; break; case 'l': conf_set_logfile(&conf, optarg); if (strncmp(optarg, "stdout", 6) == 0) log_stdout(&logger); else log_file(&logger); break; case 's': conf_set_method(&conf, optarg); break; case 'h': default: usage(argv[0]); exit(EXIT_SUCCESS); } } // Register signal handler for SIGINT signal(SIGINT, sigint_handler); if ((conf_err = conf_validate(conf)) < 0) conf_print_err(conf_err); // Daemonize the process if the dflag is set if (dflag) { log_syslog(&logger); daemonize(); } else { jail_proc(dflag); } server_create(); return 0; }
int main(int argc, char *argv[]) { int opt; bdaddr_t src_addr; int dev_id = -1; int fd; int sec = BT_SECURITY_LOW; uint8_t src_type = BDADDR_LE_PUBLIC; uint16_t mtu = 0; sigset_t mask; bool hr_visible = false; struct server *server; while ((opt = getopt_long(argc, argv, "+hvrs:t:m:i:", main_options, NULL)) != -1) { switch (opt) { case 'h': usage(); return EXIT_SUCCESS; case 'v': verbose = true; break; case 'r': hr_visible = true; break; case 's': if (strcmp(optarg, "low") == 0) sec = BT_SECURITY_LOW; else if (strcmp(optarg, "medium") == 0) sec = BT_SECURITY_MEDIUM; else if (strcmp(optarg, "high") == 0) sec = BT_SECURITY_HIGH; else { fprintf(stderr, "Invalid security level\n"); return EXIT_FAILURE; } break; case 't': if (strcmp(optarg, "random") == 0) src_type = BDADDR_LE_RANDOM; else if (strcmp(optarg, "public") == 0) src_type = BDADDR_LE_PUBLIC; else { fprintf(stderr, "Allowed types: random, public\n"); return EXIT_FAILURE; } break; case 'm': { int arg; arg = atoi(optarg); if (arg <= 0) { fprintf(stderr, "Invalid MTU: %d\n", arg); return EXIT_FAILURE; } if (arg > UINT16_MAX) { fprintf(stderr, "MTU too large: %d\n", arg); return EXIT_FAILURE; } mtu = (uint16_t) arg; break; } case 'i': dev_id = hci_devid(optarg); if (dev_id < 0) { perror("Invalid adapter"); return EXIT_FAILURE; } break; default: fprintf(stderr, "Invalid option: %c\n", opt); return EXIT_FAILURE; } } argc -= optind; argv -= optind; optind = 0; if (argc) { usage(); return EXIT_SUCCESS; } if (dev_id == -1) bacpy(&src_addr, BDADDR_ANY); else if (hci_devba(dev_id, &src_addr) < 0) { perror("Adapter not available"); return EXIT_FAILURE; } fd = l2cap_le_att_listen_and_accept(&src_addr, sec, src_type); if (fd < 0) { fprintf(stderr, "Failed to accept L2CAP ATT connection\n"); return EXIT_FAILURE; } mainloop_init(); server = server_create(fd, mtu, hr_visible); if (!server) { close(fd); return EXIT_FAILURE; } if (mainloop_add_fd(fileno(stdin), EPOLLIN | EPOLLRDHUP | EPOLLHUP | EPOLLERR, prompt_read_cb, server, NULL) < 0) { fprintf(stderr, "Failed to initialize console\n"); server_destroy(server); return EXIT_FAILURE; } printf("Running GATT server\n"); sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); mainloop_set_signal(&mask, signal_cb, NULL, NULL); print_prompt(); mainloop_run(); printf("\n\nShutting down...\n"); server_destroy(server); return EXIT_SUCCESS; }