void ThreadMgr::OnMapMgrCreated(MapMgr *mapMgr) { launch_thread(new ObjectUpdaterThread(mapMgr, mapMgr->GetInstanceID())); if(mapMgr->GetMapId() < 2 || mapMgr->GetMapId() == 530) // Main continents launch_thread(new UpdateObjectThread(mapMgr)); }
static int launch_streams(const char *name) { switch_xml_t cfg, xml, directory; int x = 0; if (!(xml = switch_xml_open_cfg(global_cf, &cfg, NULL))) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Open of %s failed\n", global_cf); return 0; } if (zstr(name)) { for (directory = switch_xml_child(cfg, "directory"); directory; directory = directory->next) { char *name = (char *) switch_xml_attr(directory, "name"); char *path = (char *) switch_xml_attr(directory, "path"); launch_thread(name, path, directory); x++; } } else if ((directory = switch_xml_find_child(cfg, "directory", "name", name))) { char *path = (char *) switch_xml_attr(directory, "path"); launch_thread(name, path, directory); x++; } switch_xml_free(xml); return x; }
int main() { try { net::tcp_socket server_socket; server_socket.bind( "127.0.0.1", 12345); server_socket.listen(); std::cout << "server socket: " << server_socket.getfd() << std::endl; while( true ) { net::tcp_socket::sockhandle handle = server_socket.accept(); if ( !handle ) return 1; launch_thread( std::bind(handle_client, handle) ); } } catch( const net::socket_exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
void client_main(unsigned short port, int connections, const char * hostName) { int i; SECStatus secStatus; PRStatus prStatus; PRInt32 rv; PRNetAddr addr; PRHostEnt hostEntry; char buffer[PR_NETDB_BUF_SIZE]; /* Setup network connection. */ prStatus = PR_GetHostByName(hostName, buffer, sizeof(buffer), &hostEntry); if (prStatus != PR_SUCCESS) { exitErr("PR_GetHostByName"); } rv = PR_EnumerateHostEnt(0, &hostEntry, port, &addr); if (rv < 0) { exitErr("PR_EnumerateHostEnt"); } secStatus = launch_thread(&threadMGR, do_connects, &addr, 1); if (secStatus != SECSuccess) { exitErr("launch_thread"); } if (connections > 1) { /* wait for the first connection to terminate, then launch the rest. */ reap_threads(&threadMGR); /* Start up the connections */ for (i = 2; i <= connections; ++i) { secStatus = launch_thread(&threadMGR, do_connects, &addr, i); if (secStatus != SECSuccess) { errWarn("launch_thread"); } } } reap_threads(&threadMGR); destroy_thread_data(&threadMGR); }
/* * Function: connect_to_server * Implementation comments: * It uses the host name and the port to create a socket and connect to a server. */ int connect_to_server(char *host_name, int port, void* (*thread_routine) (void *arg)){ int sfd; char service[PORT_LEN]; struct addrinfo hints, *result, *rp; /*Hints initialization*/ bzero(&hints, sizeof(struct addrinfo)); hints.ai_flags = 0; /*No flags*/ hints.ai_family = AF_UNSPEC; /*Either IPv4 or IPv6*/ hints.ai_socktype = SOCK_STREAM; /*TCP socket*/ hints.ai_protocol = IPPROTO_TCP; /*TCP protocol*/ hints.ai_addrlen = 0; /*Must be zero/NULL to call getaddrinfo*/ hints.ai_addr = NULL; /*Must be zero/NULL to call getaddrinfo*/ hints.ai_canonname = NULL; /*Must be zero/NULL to call getaddrinfo*/ hints.ai_next = NULL; /*Must be zero/NULL to call getaddrinfo*/ sprintf(service, "%d", port); if(getaddrinfo(host_name, service, &hints, &result) != 0){ return ERROR; } for (rp = result; rp != NULL; rp = rp->ai_next) { sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sfd != -1){ if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1){ freeaddrinfo(result); if(launch_thread(sfd, thread_routine) == ERROR){ close(sfd); return ERROR; } return sfd; } close(sfd); } } freeaddrinfo(result); return ERROR; }
static void vacuum1(int nMs){ Error err = {0}; Sqlite db = {0}; Threadset threads = {0}; opendb(&err, &db, "test.db", 1); sql_script(&err, &db, "CREATE TABLE t1(x PRIMARY KEY, y BLOB);" "CREATE INDEX i1 ON t1(y);" ); closedb(&err, &db); setstoptime(&err, nMs); sqlite3_enable_shared_cache(1); launch_thread(&err, &threads, vacuum1_thread_writer, 0); launch_thread(&err, &threads, vacuum1_thread_writer, 0); launch_thread(&err, &threads, vacuum1_thread_writer, 0); launch_thread(&err, &threads, vacuum1_thread_vacuumer, 0); join_all_threads(&err, &threads); sqlite3_enable_shared_cache(0); print_and_free_err(&err); }
pthread_t ft_launch_thread4(t_data *data, t_img *img, \ void *(*draw_func)(void *)) { t_rect *rect; if (!(rect = (t_rect *)malloc(sizeof(t_rect)))) { ft_malloc_failed(); return (0); } rect->x = 0; rect->y = img->height / 2; rect->w = img->width / 2; rect->h = img->height / 2; return (launch_thread(data, img, rect, draw_func)); }
int main(int argc, char **argv) { thread_safe_queue<int> q; q.push(10); int i; q.pop(i); std::cout << "val: " << i << std::endl; pthread_t tid; // producer( q, NUM_ITERATIONS, NUM_CONSUMERS); launch_thread( &tid, std::bind( producer, std::ref(q), NUM_ITERATIONS, NUM_CONSUMERS ) ); for(int i = 0; i < NUM_CONSUMERS; ++i) consumer( q ); }
int main() { TEST_THREAD_DATA threads_data[NUMBER_OF_TEST_THREADS]; THR_HANDLE thread_handle[NUMBER_OF_TEST_THREADS]; unsigned i; int found_error = 0; srand( (unsigned)time( NULL ) ); memset( threads_data, 0, sizeof(threads_data) ); for ( i = 0; i < NUMBER_OF_TEST_THREADS; i++ ) { threads_data[i].index = i; threads_data[i].sleep_interval_millis = get_random_value( MAX_THREAD_SLEEP_MILLIS ); thread_handle[i] = launch_thread( &threads_data[i] ); if ( !thread_handle[i] ) { fprintf( stderr, "failed to launch worker thread, error code is %d\n", LAST_ERROR() ); return EXIT_FAILURE; } } for ( i = 0; i < NUMBER_OF_TEST_THREADS; i++ ) if ( join_thread( thread_handle[i] ) != 0 ) { fprintf( stderr, "failed to join thread %d, error code is %d\n", i, LAST_ERROR() ); return EXIT_FAILURE; } for ( i = 0; i < NUMBER_OF_TEST_THREADS; i++ ) { if( threads_data[i].error_occured ) { fprintf( stderr, "error occured at thread %d: %s\n", i, threads_data[i].error_message ); found_error = 1; } } if ( found_error ) return EXIT_FAILURE; // printf( "test ended successfully\n"); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int threads = 8; if (argc > 1) threads = atoi(argv[1]); if (threads > MAX_THREADS) threads = MAX_THREADS; printf("Testing with %d threads\n", threads); for (int i = 0; i < threads; i++) { launch_thread(i); } for (int i = 0; i < threads; i++) { wait_thread(i); } return 0; }
int main(int argc, char **argv) { int socket, client_socket; int port = IRC_DEFAULT_PORT; /*Parameters processing*/ if (argc != 1 && argc != 2) { printf("%s <port (optional)>\n", argv[0]); return (EXIT_FAILURE); } else if (argc == 2) { port = atoi(argv[1]); } /*Runs in background*/ if (daemonize(SERVER_LOG_IDENT) == ERROR) { irc_exit_message(); return (EXIT_FAILURE); } /*Initializes server*/ socket = init_server(port, SERVER_MAX_CONNECTIONS); if (socket <= 0) { irc_exit_message(); exit(EXIT_FAILURE); } /*Initializes IRC server data*/ irc_server_data_init(); /*Accepts connexions and takes charge of them*/ while (1) { client_socket = accept_connections(socket); nbjoin_threads(); if (launch_thread(client_socket, irc_thread_routine) != OK) { syslog(LOG_ERR, "Server: Failed while launching a thread: %s", strerror(errno)); } } return (EXIT_SUCCESS); }
/*=========================================================================== *===========================================================================*/ void change_adapter_status(struct mg_connection *c, const struct mg_request_info *ri, void *user_data) { struct Squirrel *squirrel = (struct Squirrel *)user_data; char *status = mg_get_var(c, "status"); char *channel = mg_get_var(c, "channel"); char *adapter_name = mg_get_var(c, "if"); unsigned interface_channel = 0; if (status && channel && adapter_name) { unsigned is_running = squirrel_get_interface_status(squirrel, adapter_name, &interface_channel); unsigned new_channel; if (strcmp(channel, "scan") == 0) new_channel = (unsigned)-1; else if (isdigit(channel[0])) new_channel = atoi(channel); else new_channel = 0; if (is_running && strcmp(status, "monitor") != 0) { /* Turn off the adapter */ squirrel_set_interface_status(squirrel, adapter_name, 0, 0); X(c, "<b>Turned off adapter</b>\n"); } else if (!is_running && strcmp(status, "monitor") == 0) { launch_thread(squirrel, adapter_name); squirrel_set_interface_status(squirrel, adapter_name, 1, new_channel); X(c, "<b>Turned on adapter, channel %u</b>\n", new_channel); } else if (is_running && interface_channel != new_channel) { squirrel_set_interface_status(squirrel, adapter_name, 1, new_channel); X(c, "<b>Changed channel to %u</b>\n", new_channel); } else X(c, "<b>Nothing changed</b>\n"); } if (status) free(status); if (channel) free(channel); }
void fill_slots(jobtype ptype, pkgstate* state) { size_t i; pkg_exec* item; pkgdata* pkg; int* slots = (ptype == JT_DOWNLOAD) ? &state->slots.dl_slots : &state->slots.build_slots; sblist* queue = (ptype == JT_DOWNLOAD) ? state->dl_queue : state->build_queue; for(i = 0; *slots && i < sblist_getsize(queue); i++) { item = sblist_get(queue, i); if(item->pid == -1) { pkg = packagelist_get(state->package_list, item->name, stringptr_hash(item->name)); if(ptype == JT_DOWNLOAD || has_all_deps(state, pkg)) { if(ptype == JT_BUILD && !pkg->verified) { if (! (pkg->verified = !(verify_tarball(&state->cfg, pkg)))) { log_put(2, VARISL("WARNING: "), VARIS(item->name), VARISL(" failed to verify! please delete its tarball and retry downloading it."), NULL); continue; } } launch_thread(ptype, state, item, pkg); (*slots)--; } } } }
static void checkpoint_starvation_main(int nMs, CheckpointStarvationCtx *p){ Error err = {0}; Sqlite db = {0}; Threadset threads = {0}; int nInsert = 0; int i; opendb(&err, &db, "test.db", 1); sql_script(&err, &db, "PRAGMA page_size = 1024;" "PRAGMA journal_mode = WAL;" "CREATE TABLE t1(x);" ); setstoptime(&err, nMs); for(i=0; i<4; i++){ launch_thread(&err, &threads, checkpoint_starvation_reader, 0); usleep(CHECKPOINT_STARVATION_READMS*1000/4); } sqlite3_wal_hook(db.db, checkpoint_starvation_walhook, (void *)p); while( !timetostop(&err) ){ sql_script(&err, &db, "INSERT INTO t1 VALUES(randomblob(1200))"); nInsert++; } printf(" Checkpoint mode : %s\n", p->eMode==SQLITE_CHECKPOINT_PASSIVE ? "PASSIVE" : "RESTART" ); printf(" Peak WAL : %d frames\n", p->nMaxFrame); printf(" Transaction count: %d transactions\n", nInsert); join_all_threads(&err, &threads); closedb(&err, &db); print_and_free_err(&err); }
void draw_set(t_image *img, t_frac *f) { t_data_thread dt; pthread_t draw_threads[NUM_THREADS]; int i; int starts[NUM_THREADS]; int ends[NUM_THREADS]; init_starts_ends(starts, ends); i = 0; dt.img = img; dt.f = f; pthread_mutex_init(&dt.frac_mutex, NULL); while (i < NUM_THREADS) { dt.start = starts[i]; dt.f->p.x = dt.start; dt.end = ends[i]; launch_thread(&draw_threads[i], draw_worker, &dt); wait_thread(draw_threads[i]); i++; } pthread_mutex_destroy(&dt.frac_mutex); }
void epollEngine::SpawnThreads() { launch_thread(new SocketEngineThread(this)); }
void SocketMgr::SpawnWorkerThreads() { int tc = 1; for(int i = 0; i < tc; ++i) launch_thread(new SocketWorkerThread()); }
bool Master::Run(int argc, char ** argv) { #ifdef WIN32 char * config_file = "antrix.conf"; char * realm_config_file = "realms.conf"; #else char * config_file = CONFDIR "/antrix.conf"; char * realm_config_file = CONFDIR "/realms.conf"; #endif int file_log_level = DEF_VALUE_NOT_SET; int screen_log_level = DEF_VALUE_NOT_SET; int do_check_conf = 0; int do_version = 0; struct antrix_option longopts[] = { { "checkconf", antrix_no_argument, &do_check_conf, 1 }, { "screenloglevel", antrix_required_argument, &screen_log_level, 1 }, { "fileloglevel", antrix_required_argument, &file_log_level, 1 }, { "version", antrix_no_argument, &do_version, 1 }, { "conf", antrix_required_argument, NULL, 'c' }, { "realmconf", antrix_required_argument, NULL, 'r' }, { 0, 0, 0, 0 } }; char c; while ((c = antrix_getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1) { switch (c) { case 'c': config_file = new char[strlen(antrix_optarg)]; strcpy(config_file, antrix_optarg); break; case 'r': realm_config_file = new char[strlen(antrix_optarg)]; strcpy(realm_config_file, antrix_optarg); break; case 0: break; default: sLog.m_fileLogLevel = -1; sLog.m_screenLogLevel = 3; printf("Usage: %s [--checkconf] [--screenloglevel <level>] [--fileloglevel <level>] [--conf <filename>] [--realmconf <filename>] [--version]\n", argv[0]); return true; } } // Startup banner if(!do_version && !do_check_conf) { launch_thread(new TextLoggerThread); sLog.Init(-1, 3); } else { sLog.m_fileLogLevel = -1; sLog.m_screenLogLevel = 3; } sLog.outString("=============================================================================="); sLog.outString(BANNER, g_getRevision()); sLog.outString(""); sLog.outString("Copyright (c) 2007 Antrix Team. This software is under the QPL license, for"); sLog.outString("more information look under the COPYING file in this distribution."); sLog.outString("=============================================================================="); sLog.outString(""); if(do_version) return true; if(do_check_conf) { printf("Checking config file: %s\n", config_file); if(Config.MainConfig.SetSource(config_file, true)) printf(" Passed without errors.\n"); else printf(" Encountered one or more errors.\n"); printf("\nChecking config file: %s\n", realm_config_file); if(Config.RealmConfig.SetSource(realm_config_file, true)) printf(" Passed without errors.\n"); else printf(" Encountered one or more errors.\n"); /* test for die variables */ string die; if(Config.MainConfig.GetString("die", "msg", &die) || Config.MainConfig.GetString("die2", "msg", &die)) printf("Die directive received: %s", die.c_str()); return true; } sLog.outString("The key combination <Ctrl-C> will safely shut down the server at any time."); sLog.outString(""); sLog.outString("Initializing File Loggers..."); Crash_Log = new TextLogger(FormatOutputString("logs", "CrashLog", true).c_str(), false); sLog.outString("Initializing Random Number Generators..."); uint32 seed = time(NULL); new MTRand(seed); srand(seed); sLog.outString("Starting Thread Manager...\n"); new ThreadMgr; uint32 LoadingTime = getMSTime(); sLog.outColor(TNORMAL, "Loading Config Files...\n"); sLog.outColor(TYELLOW, " >> %s :: ", config_file); if(Config.MainConfig.SetSource(config_file)) { sLog.outColor(TGREEN, "ok!"); sLog.outColor(TNORMAL, "\n"); } else { sLog.outColor(TRED, "fail."); sLog.outColor(TNORMAL, "\n"); return false; } /* test for die variables */ string die; if(Config.MainConfig.GetString("die", "msg", &die) || Config.MainConfig.GetString("die2", "msg", &die)) { printf("Die directive received: %s", die.c_str()); return false; } sLog.outColor(TYELLOW, " >> %s :: ", realm_config_file); if(Config.RealmConfig.SetSource(realm_config_file)) { sLog.outColor(TGREEN, "ok!"); sLog.outColor(TNORMAL, "\n\n"); } else { sLog.outColor(TRED, "fail."); sLog.outColor(TNORMAL, "\n\n"); return false; } if(!_StartDB()) { return false; } sLog.outString(""); ScriptSystem = new ScriptEngine; ScriptSystem->Reload(); new EventMgr; new World; // open cheat log file Anticheat_Log = new SessionLogWriter(FormatOutputString("logs", "cheaters", false).c_str(), false); GMCommand_Log = new SessionLogWriter(FormatOutputString("logs", "gmcommand", false).c_str(), false); /* load the config file */ sWorld.Rehash(false); /* set new log levels */ if(screen_log_level != (int)DEF_VALUE_NOT_SET) sLog.SetScreenLoggingLevel(screen_log_level); if(file_log_level != (int)DEF_VALUE_NOT_SET) sLog.SetFileLoggingLevel(file_log_level); // Initialize Opcode Table WorldSession::InitPacketHandlerTable(); string host = Config.MainConfig.GetStringDefault("Listen", "Host", DEFAULT_HOST); int wsport = Config.MainConfig.GetIntDefault("Listen", "WorldServerPort", DEFAULT_WORLDSERVER_PORT); new ScriptMgr; sWorld.SetInitialWorldSettings(); sWorld.SetStartTime((uint32)time(NULL)); _HookSignals(); launch_thread(new CConsoleThread); uint32 realCurrTime, realPrevTime; realCurrTime = realPrevTime = getMSTime(); // initialize thread system sThreadMgr.Initialize(); // Socket loop! uint32 start; uint32 diff; uint32 last_time = now(); uint32 etime; uint32 next_printout = getMSTime(), next_send = getMSTime(); // Start Network Subsystem sLog.outString("Starting network subsystem..."); new SocketMgr; new SocketGarbageCollector; sSocketMgr.SpawnWorkerThreads(); sScriptMgr.LoadScripts(); sLog.outString("Threading system initialized, currently %u threads are active.", sThreadMgr.GetThreadCount()); LoadingTime = getMSTime() - LoadingTime; sLog.outString ("\nServer is ready for connections. Startup time: %ums\n", LoadingTime ); /* write pid file */ FILE * fPid = fopen("antrix.pid", "w"); if(fPid) { uint32 pid; #ifdef WIN32 pid = GetCurrentProcessId(); #else pid = getpid(); #endif fprintf(fPid, "%u", (unsigned int)pid); fclose(fPid); } #ifndef CLUSTERING /* Connect to realmlist servers / logon servers */ new LogonCommHandler(); sLogonCommHandler.Startup(); // Create listener ListenSocket<WorldSocket> * ls = new ListenSocket<WorldSocket>(host.c_str(), wsport); bool listnersockcreate = ls->IsOpen(); while(!m_stopEvent && listnersockcreate) #else new ClusterInterface; sClusterInterface.ConnectToRealmServer(); while(!m_stopEvent) #endif { start = now(); diff = start - last_time; #ifndef CLUSTERING sLogonCommHandler.UpdateSockets(); ls->Update(); #else sClusterInterface.Update(); #endif sSocketGarbageCollector.Update(); /* UPDATE */ last_time = now(); etime = last_time - start; if(m_ShutdownEvent) { if(getMSTime() >= next_printout) { if(m_ShutdownTimer > 60000.0f) { if(!((int)(m_ShutdownTimer)%60000)) sLog.outString("Server shutdown in %i minutes.", (int)(m_ShutdownTimer / 60000.0f)); } else sLog.outString("Server shutdown in %i seconds.", (int)(m_ShutdownTimer / 1000.0f)); next_printout = getMSTime() + 500; } if(getMSTime() >= next_send) { // broadcast packet. WorldPacket data(20); data.SetOpcode(SMSG_SERVER_MESSAGE); data << uint32(SERVER_MSG_SHUTDOWN_TIME); int time = m_ShutdownTimer / 1000; if(time > 0) { int mins = 0, secs = 0; if(time > 60) mins = time / 60; if(mins) time -= (mins*60); secs = time; char str[20]; snprintf(str, 20, "%02u:%02u", mins, secs); data << str; sWorld.SendGlobalMessage(&data, NULL); } next_send = getMSTime() + 1000; } if(diff >= m_ShutdownTimer) break; else m_ShutdownTimer -= diff; } Database_Character->CheckConnections(); Database_World->CheckConnections(); sWorld.UpdateQueuedSessions(diff); if(50 > etime) Sleep(50 - etime); } _UnhookSignals(); CConsoleThread *thread = (CConsoleThread*)sThreadMgr.GetThreadByType(THREADTYPE_CONSOLEINTERFACE); ASSERT(thread); thread->SetThreadState(THREADSTATE_TERMINATE); // have to cleanup manually. sThreadMgr.RemoveThread(thread); sLog.outString("Killing all sockets and network subsystem."); #ifndef CLUSTERING ls->Close(); delete ls; #endif #ifdef WIN32 sSocketMgr.ShutdownThreads(); #endif sSocketMgr.CloseAll(); // begin server shutdown time_t st = time(NULL); sLog.outString("Server shutdown initiated at %s", ctime(&st)); // send a query to wake it up if its inactive sLog.outString("Executing pending database queries and closing database thread..."); // kill the database thread first so we don't lose any queries/data ((MySQLDatabase*)Database_Character)->SetThreadState(THREADSTATE_TERMINATE); ((MySQLDatabase*)Database_World)->SetThreadState(THREADSTATE_TERMINATE); CharacterDatabase.Execute("UPDATE characters SET online = 0"); WorldDatabase.Execute("UPDATE characters SET online = 0"); // wait for it to finish its work while(((MySQLDatabase*)Database_Character)->ThreadRunning || ((MySQLDatabase*)Database_World)->ThreadRunning) { Sleep(100); } sThreadMgr.RemoveThread(((MySQLDatabase*)Database_Character)); sThreadMgr.RemoveThread(((MySQLDatabase*)Database_World)); sLog.outString("All pending database operations cleared.\n"); sWorld.SaveAllPlayers(); sLog.outString(""); delete LogonCommHandler::getSingletonPtr(); sWorld.ShutdownClasses(); sLog.outString("\nDeleting World..."); delete World::getSingletonPtr(); sLog.outString("Deleting Event Manager..."); delete EventMgr::getSingletonPtr(); sLog.outString("Terminating MySQL connections...\n"); _StopDB(); sLog.outString("Deleting Network Subsystem..."); delete SocketMgr::getSingletonPtr(); delete SocketGarbageCollector::getSingletonPtr(); sLog.outString("Deleting Script Engine..."); delete ScriptSystem; sLog.outString("\nServer shutdown completed successfully.\n"); // close the logs TextLogger::Thread->Die(); #ifdef WIN32 WSACleanup(); // Terminate Entire Application //HANDLE pH = OpenProcess(PROCESS_TERMINATE, TRUE, GetCurrentProcessId()); //TerminateProcess(pH, 0); //CloseHandle(pH); #endif return true; }
void SelectEngine::SpawnThreads() { launch_thread(new SocketEngineThread(this)); }
void kqueueEngine::SpawnThreads() { launch_thread(new SocketEngineThread(this)); }
void testScenario1(void) { launch_thread(); // thread shared }
/*=========================================================================== *===========================================================================*/ void display_adapter(struct mg_connection *c, const struct mg_request_info *ri, void *user_data) { struct Squirrel *squirrel = (struct Squirrel *)user_data; char adapter_name[256]; char description[256]; unsigned exists; const char *driver = ""; unsigned interface_channel = 0; pixie_enter_critical_section(squirrel->cs); if (memcmp(ri->uri, "/adapter/", 9) != 0) { mg_printf(c, "404 Not Found\r\nConnection: closed\r\n\r\n"); goto _return; } else sprintf_s(adapter_name, sizeof(adapter_name), "%s", ri->uri+9); if (strlen(adapter_name) > 5 && memcmp(adapter_name+strlen(adapter_name)-5, ".html", 5) == 0) adapter_name[strlen(adapter_name)-5] = '\0'; if (strlen(adapter_name) > 7 && memcmp(adapter_name, "airpcap", 7) == 0 && strlen(adapter_name) < sizeof(adapter_name)-5) { memmove(adapter_name+4, adapter_name, strlen(adapter_name)+1); memcpy(adapter_name, "\\\\.\\", 4); } exists = adapter_description(adapter_name, description, sizeof(description)); if (!exists) { mg_printf(c, "404 Not Found\r\nConnection: closed\r\n\r\n"); goto _return; } if (strstr(adapter_name, "\\airpcap")) { driver = "airpcap"; } else { driver = "ndis"; } mg_headers_ok(c, "text/html"); X(c, "Connection: close\r\n"); X(c, "\r\n"); //X(c, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\r\n"); X(c,"<html>\n"); X(c,"<head>\n"); X(c," <title>Squirrel WiFi monitor / Adapter</title>\n"); X(c," <link rel=\"stylesheet\" type=\"text/css\" href=\"../squirrel.css\" />\n"); X(c," <link rel=\"Shortcut Icon\" href=\"../favicon.ico\" type=\"image/x-icon\">\n"); X(c,"</head>\n"); X(c,"<body>\n"); display_topmenu(c, ri, user_data, 0); /* * Do any necessary changes */ { char *status = mg_get_var(c, "status"); char *channel = mg_get_var(c, "channel"); if (status && channel) { unsigned is_running = squirrel_get_interface_status(squirrel, adapter_name, &interface_channel); unsigned new_channel; if (strcmp(channel, "scan") == 0) new_channel = (unsigned)-1; else if (isdigit(channel[0])) new_channel = atoi(channel); else new_channel = 0; if (is_running && strcmp(status, "monitor") != 0) { /* Turn off the adapter */ squirrel_set_interface_status(squirrel, adapter_name, 0, 0); X(c, "<b>Turned off adapter</b>\n"); } else if (!is_running && strcmp(status, "monitor") == 0) { launch_thread(squirrel, adapter_name); squirrel_set_interface_status(squirrel, adapter_name, 1, new_channel); X(c, "<b>Turned on adapter, channel %u</b>\n", new_channel); } else if (is_running && interface_channel != new_channel) { squirrel_set_interface_status(squirrel, adapter_name, 1, new_channel); X(c, "<b>Changed channel to %u</b>\n", new_channel); } else X(c, "<b>Nothing changed</b>\n"); } if (status) free(status); if (channel) free(channel); } X(c, "<table class=\"adapter\">\n"); X(c, " <tr><th>Adapter:</th><td>%s</td></tr>\n", adapter_name); X(c, " <tr><th>Description:</th><td>%s</td></tr>\n", description); X(c, " <tr><th>Driver:</th><td>%s</td></tr>\n", driver); X(c, " <tr><th>Monitor Mode:</th><td>%s</td></tr>\n", can_monitor_mode(adapter_name)?"yes":"no"); X(c, " <tr><th>Can Transmit:</th><td>%s</td></tr>\n", can_transmit(adapter_name)?"yes":"no"); if (squirrel_get_interface_status(squirrel, adapter_name, &interface_channel)) { X(c, " <tr><th>Status:</th><td>%s</td></tr>\n", "monitoring"); if (interface_channel == 0) X(c, " <tr><th>Channel:</th><td>%s</td></tr>\n", ""); else if (interface_channel == (unsigned)-1) X(c, " <tr><th>Channel:</th><td>%s</td></tr>\n", "scan"); else X(c, " <tr><th>Channel:</th><td>%u</td></tr>\n", interface_channel); } else { X(c, " <tr><th>Status:</th><td>%s</td></tr>\n", "off"); X(c, " <tr><th>Channel:</th><td>%s</td></tr>\n", ""); } X(c, "</table>\n"); X(c, "<hr/>\n"); X(c, "<form action=\"%s.html\">\n", adapter_name); X(c, " <input type=\"radio\" name=\"status\" value=\"monitor\" /> Monitor<br/>\n"); X(c, " <input type=\"radio\" name=\"status\" value=\"off\" /> Off<br/>\n"); X(c, " Channel: <input type=\"text\" name=\"channel\" value=\"scan\"/><br/>\n"); X(c, " <input type=\"submit\" value=\"Submit\">\n"); X(c, "</form>\n"); _return: pixie_leave_critical_section(squirrel->cs); }
int main (int argc, char **argv) { int last_argc = -1; if (argc) { argc--; argv++; } while (argc && last_argc != argc ) { last_argc = argc; if (!strcmp (*argv, "--help")) { puts ( "usage: ./t-poll [options]\n" "\n" "Options:\n" " --verbose Show what is going on\n" " --debug Flyswatter\n" ); exit (0); } if (!strcmp (*argv, "--verbose")) { verbose = 1; argc--; argv++; } else if (!strcmp (*argv, "--debug")) { verbose = debug = 1; argc--; argv++; } } if (!gpg_error_check_version (GPG_ERROR_VERSION)) { die ("gpg_error_check_version returned an error"); errorcount++; } peer_stdin.name = "stdin producer"; create_pipe (&test_stdin, &peer_stdin.stream); peer_stdout.name = "stdout consumer"; create_pipe (&peer_stdout.stream, &test_stdout); peer_stderr.name = "stderr consumer"; create_pipe (&peer_stderr.stream, &test_stderr); if (es_set_nonblock (test_stdin, 1)) fail ("error setting test_stdin to nonblock: %s\n", strerror (errno)); if (es_set_nonblock (test_stdout, 1)) fail ("error setting test_stdout to nonblock: %s\n", strerror (errno)); if (es_set_nonblock (test_stderr, 1)) fail ("error setting test_stderr to nonblock: %s\n", strerror (errno)); launch_thread (producer_thread, &peer_stdin ); launch_thread (consumer_thread, &peer_stdout); launch_thread (consumer_thread, &peer_stderr); test_poll (); show ("Waiting for threads to terminate...\n"); es_fclose (test_stdin); es_fclose (test_stdout); es_fclose (test_stderr); peer_stdin.stop_me = 1; peer_stdout.stop_me = 1; peer_stderr.stop_me = 1; join_thread (&peer_stdin); join_thread (&peer_stdout); join_thread (&peer_stderr); return errorcount ? 1 : 0; }
void ScriptMgr::SpawnThread(WowdThread * thread) { launch_thread(thread); }