void test_file_notification(void**) { int temp = 1; const char* test_dir = "t2-output/test_dir"; const char* test_dir_2 = "t2-output/2_test_dir"; const char* test_dir_3 = "t2-output/3_test_dir"; const char* filename_2 = "t2-output/test_dir/test_file_2"; s_filename = "t2-output/test_dir/test_file.dll"; s_filename_2 = "t2-output/2_test_dir/test_file.txt"; s_filename_3 = "t2-output/3_test_dir/test_file.bin"; s_filename_4 = "t2-output/3_test_dir/test_file.so"; s_filename_5 = "t2-output/3_test_dir/test_file.exe"; fs_remove_directory(test_dir); fs_make_directory(test_dir); fs_remove_directory(test_dir_2); fs_make_directory(test_dir_2); fs_remove_directory(test_dir_3); fs_make_directory(test_dir_3); FILE* t = fopen(filename_2, "wb"); fwrite(&temp, 4, 1, t); fclose(t); FileMonitor_addPath(test_dir, "*", fileNotifaction, &s_user_data_1); thread_sleep(200); // Test notification when writing one file t = fopen(s_filename, "wb"); fclose(t); thread_sleep(1000); FileMonitor_update(); thread_sleep(400); assert_int_equal(s_checkPhase, 1); fs_copy_file(filename_2, s_filename); thread_sleep(1000); FileMonitor_update(); thread_sleep(400); assert_int_equal(s_checkPhase, 2); FileMonitor_addPath(test_dir_2, "txt", fileNotifaction2, &s_user_data_2); thread_sleep(1000); fs_copy_file(filename_2, s_filename_2); thread_sleep(1200); FileMonitor_update(); assert_int_equal(s_checkPhase, 3); FileMonitor_removePath(test_dir); // Except no notifactions for this fs_remove_file(s_filename); FileMonitor_update(); thread_sleep(1000); FileMonitor_update(); thread_sleep(400); assert_int_equal(s_checkPhase, 3); FileMonitor_addPath(test_dir_3, "bin;so", fileNotifaction3, &s_user_data_3); thread_sleep(1000); fs_copy_file(filename_2, s_filename_3); thread_sleep(1200); FileMonitor_update(); assert_int_equal(s_checkPhase, 4); thread_sleep(1000); fs_copy_file(filename_2, s_filename_4); thread_sleep(1200); FileMonitor_update(); assert_int_equal(s_checkPhase, 5); thread_sleep(1000); fs_copy_file(filename_2, s_filename_5); thread_sleep(1200); FileMonitor_update(); assert_int_equal(s_checkPhase, 5); FileMonitor_close(); }
void Run(unsigned short Port, NETADDR Dest) { NETADDR Src = {NETTYPE_IPV4, {0,0,0,0}, Port}; NETSOCKET Socket = net_udp_create(Src, 0); char aBuffer[1024*2]; int ID = 0; int Delaycounter = 0; while(1) { static int Lastcfg = 0; int n = ((time_get()/time_freq())/m_ConfigInterval) % m_ConfigNumpingconfs; CPingConfig Ping = m_aConfigPings[n]; if(n != Lastcfg) dbg_msg("crapnet", "cfg = %d", n); Lastcfg = n; // handle incomming packets while(1) { // fetch data int DataTrash = 0; NETADDR From; int Bytes = net_udp_recv(Socket, &From, aBuffer, 1024*2); if(Bytes <= 0) break; if((rand()%100) < Ping.m_Loss) // drop the packet { if(m_ConfigLog) dbg_msg("crapnet", "dropped packet"); continue; } // create new packet CPacket *p = (CPacket *)mem_alloc(sizeof(CPacket)+Bytes, 1); if(net_addr_comp(&From, &Dest) == 0) p->m_SendTo = Src; // from the server else { Src = From; // from the client p->m_SendTo = Dest; } // queue packet p->m_pPrev = m_pLast; p->m_pNext = 0; if(m_pLast) m_pLast->m_pNext = p; else { m_pFirst = p; m_pLast = p; } m_pLast = p; // set data in packet p->m_Timestamp = time_get(); p->m_DataSize = Bytes; p->m_ID = ID++; mem_copy(p->m_aData, aBuffer, Bytes); if(ID > 20 && Bytes > 6 && DataTrash) { p->m_aData[6+(rand()%(Bytes-6))] = rand()&255; // modify a byte if((rand()%10) == 0) { p->m_DataSize -= rand()%32; if(p->m_DataSize < 6) p->m_DataSize = 6; } } if(Delaycounter <= 0) { if(Ping.m_Delay) p->m_Timestamp += (time_freq()*1000)/Ping.m_Delay; Delaycounter = Ping.m_DelayFreq; } Delaycounter--; if(m_ConfigLog) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&From, aAddrStr, sizeof(aAddrStr), true); dbg_msg("crapnet", "<< %08d %s (%d)", p->m_ID, aAddrStr, p->m_DataSize); } } // /*while(1) {*/ CPacket *p = 0; CPacket *pNext = m_pFirst; while(1) { p = pNext; if(!p) break; pNext = p->m_pNext; if((time_get()-p->m_Timestamp) > m_CurrentLatency) { char aFlags[] = " "; if(m_ConfigReorder && (rand()%2) == 0 && p->m_pNext) { aFlags[0] = 'R'; p = m_pFirst->m_pNext; } if(p->m_pNext) p->m_pNext->m_pPrev = p->m_pPrev; else m_pLast = p->m_pPrev; if(p->m_pPrev) p->m_pPrev->m_pNext = p->m_pNext; else m_pFirst = p->m_pNext; /*CPacket *cur = first; while(cur) { dbg_assert(cur != p, "p still in list"); cur = cur->next; }*/ // send and remove packet //if((rand()%20) != 0) // heavy packetloss net_udp_send(Socket, &p->m_SendTo, p->m_aData, p->m_DataSize); // update lag double Flux = rand()/(double)RAND_MAX; int MsSpike = Ping.m_Spike; int MsFlux = Ping.m_Flux; int MsPing = Ping.m_Base; m_CurrentLatency = ((time_freq()*MsPing)/1000) + (int64)(((time_freq()*MsFlux)/1000)*Flux); // 50ms if(MsSpike && (p->m_ID%100) == 0) { m_CurrentLatency += (time_freq()*MsSpike)/1000; aFlags[1] = 'S'; } if(m_ConfigLog) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&p->m_SendTo, aAddrStr, sizeof(aAddrStr), true); dbg_msg("crapnet", ">> %08d %s (%d) %s", p->m_ID, aAddrStr, p->m_DataSize, aFlags); } mem_free(p); } } thread_sleep(1); } }
static void *_stats_thread(void *arg) { stats_event_t *event; stats_event_t *copy; stats_node_t *node; stats_node_t *anode; stats_source_t *snode; stats_source_t *asnode; event_listener_t *listener; avl_node *avlnode; while (_stats_running) { thread_mutex_lock(&_global_event_mutex); if (_global_event_queue != NULL) { /* grab the next event from the queue */ event = _global_event_queue; _global_event_queue = event->next; event->next = NULL; thread_mutex_unlock(&_global_event_mutex); thread_mutex_lock(&_stats_mutex); if (event->source == NULL) { /* we have a global event */ if (event->value != NULL) { /* adding/updating */ node = _find_node(_stats.global_tree, event->name); if (node == NULL) { /* add node */ anode = (stats_node_t *)malloc(sizeof(stats_node_t)); anode->name = (char *)strdup(event->name); anode->value = (char *)strdup(event->value); avl_insert(_stats.global_tree, (void *)anode); } else { /* update node */ free(node->value); node->value = (char *)strdup(event->value); } } else { /* we're deleting */ node = _find_node(_stats.global_tree, event->name); if (node != NULL) avl_delete(_stats.global_tree, (void *)node, _free_stats); } } else { /* we have a source event */ snode = _find_source(_stats.source_tree, event->source); if (snode != NULL) { /* this is a source we already have a tree for */ if (event->value != NULL) { /* we're add/updating */ node = _find_node(snode->stats_tree, event->name); if (node == NULL) { /* adding node */ anode = (stats_node_t *)malloc(sizeof(stats_node_t)); anode->name = (char *)strdup(event->name); anode->value = (char *)strdup(event->value); avl_insert(snode->stats_tree, (void *)anode); } else { /* updating node */ free(node->value); node->value = (char *)strdup(event->value); } } else { /* we're deleting */ node = _find_node(snode->stats_tree, event->name); if (node != NULL) { avl_delete(snode->stats_tree, (void *)node, _free_stats); avlnode = avl_get_first(snode->stats_tree); if (avlnode == NULL) { avl_delete(_stats.source_tree, (void *)snode, _free_source_stats); } } } } else { /* this is a new source */ asnode = (stats_source_t *)malloc(sizeof(stats_source_t)); asnode->source = (char *)strdup(event->source); asnode->stats_tree = avl_tree_new(_compare_stats, NULL); anode = (stats_node_t *)malloc(sizeof(stats_node_t)); anode->name = (char *)strdup(event->name); anode->value = (char *)strdup(event->value); avl_insert(asnode->stats_tree, (void *)anode); avl_insert(_stats.source_tree, (void *)asnode); } } /* now we have an event that's been processed into the running stats */ /* this event should get copied to event listeners' queues */ listener = _event_listeners; while (listener) { copy = _copy_event(event); thread_mutex_lock(listener->mutex); _add_event_to_queue(copy, listener->queue); thread_mutex_unlock(listener->mutex); listener = listener->next; } thread_cond_broadcast(&_event_signal_cond); /* now we need to destroy the event */ _free_event(event); thread_mutex_unlock(&_stats_mutex); continue; } else { thread_mutex_unlock(&_global_event_mutex); } thread_sleep(300000); } /* wake the other threads so they can shut down cleanly */ thread_cond_broadcast(&_event_signal_cond); thread_exit(0); return NULL; }
int moboot_menu(unsigned x, unsigned y, char **entries, unsigned init, unsigned total, unsigned timeout) { unsigned curpos, i, max, keys, is_pressed, has_timeout, countdown; time_t tick; max = total - 1; curpos = init; if (timeout) { has_timeout = 1; countdown = timeout; tick = current_time() + 1000; } else { has_timeout = 0; } while (1) { for (i = 0; i < total; i++) { if (i == curpos) { fbcon_set_colors(0, 0, 255, 0, 0, 0); } else { fbcon_set_colors(0, 0, 0, 0, 0, 255); } fbcon_setpos(x, y + i); printf("%s", entries[i]); } fbcon_set_colors(0, 0, 0, 0, 0, 255); is_pressed = gpiokeys_poll(KEY_ALL); while (1) { if (has_timeout) { if (current_time() > tick) { tick += 1000; countdown--; if (!countdown) { return curpos; } } fbcon_setpos(x, y + total + 1); printf("timeout in %d ", countdown); } thread_sleep(20); keys = gpiokeys_poll(KEY_ALL); if (has_timeout && keys) { fbcon_setpos(x, y + total + 1); printf(" "); has_timeout = 0; } if (is_pressed && !keys) { if (is_pressed & KEY_SELECT) { return curpos; } if (is_pressed & KEY_UP) { if (curpos == 0) { curpos = max; } else { curpos--; } } if (is_pressed & KEY_DOWN) { if (curpos == max) { curpos = 0; } else { curpos++; } } break; } else if (keys) { is_pressed = keys; } } } }
int process_wait(process_t* proc) { #if FOUNDATION_PLATFORM_POSIX int cstatus; pid_t ret; #endif #if FOUNDATION_PLATFORM_WINDOWS if (!proc->hp) return proc->code; while (GetExitCodeProcess(proc->hp, (LPDWORD)&proc->code)) { if ((proc->code != (int)STILL_ACTIVE) || (proc->flags & PROCESS_DETACHED)) break; thread_sleep(50); proc->code = -1; } if ((proc->code == (int)STILL_ACTIVE) && (proc->flags & PROCESS_DETACHED)) return PROCESS_STILL_ACTIVE; if (proc->ht) CloseHandle(proc->ht); if (proc->hp) CloseHandle(proc->hp); proc->hp = 0; proc->ht = 0; #elif FOUNDATION_PLATFORM_POSIX if (!proc->pid) return proc->code; # if FOUNDATION_PLATFORM_MACOSX if (proc->flags & PROCESS_MACOSX_USE_OPENAPPLICATION) { if (proc->kq) { struct kevent event; ret = kevent(proc->kq, 0, 0, &event, 1, 0); if (ret != 1) { int err = errno; string_const_t errmsg = system_error_message(err); log_warnf(0, WARNING_SYSTEM_CALL_FAIL, STRING_CONST("Unable to wait on process, failed to read event from kqueue: %.*s (%d)"), STRING_FORMAT(errmsg), err); } close(proc->kq); proc->kq = 0; } else { log_warn(0, WARNING_INVALID_VALUE, STRING_CONST("Unable to wait on a process started with PROCESS_MACOSX_USE_OPENAPPLICATION and no kqueue")); return PROCESS_WAIT_FAILED; } proc->pid = 0; proc->code = 0; return proc->code; } # endif cstatus = 0; ret = waitpid(proc->pid, &cstatus, (proc->flags & PROCESS_DETACHED) ? WNOHANG : 0); if (ret > 0) { if (WIFEXITED(cstatus)) proc->code = (int)((char)WEXITSTATUS(cstatus)); else if (WIFSIGNALED(cstatus)) { proc->code = PROCESS_TERMINATED_SIGNAL; #ifdef WCOREDUMP //if( WCOREDUMP( cstatus ) ) //... #endif //proc->signal = WTERMSIG( cstatus ); } else { proc->code = PROCESS_WAIT_FAILED; } proc->pid = 0; } else { int err = errno; if ((ret == 0) && (proc->flags & PROCESS_DETACHED)) return PROCESS_STILL_ACTIVE; if ((ret < 0) && (err == EINTR)) return PROCESS_WAIT_INTERRUPTED; string_const_t errmsg = system_error_message(err); log_warnf(0, WARNING_INVALID_VALUE, STRING_CONST("waitpid(%d) failed: %.*s (%d) (returned %d)"), proc->pid, STRING_FORMAT(errmsg), err, ret); return PROCESS_WAIT_FAILED; } #elif FOUNDATION_PLATFORM_PNACL //Not supported #else #error Not implemented #endif return proc->code; }
static int do_reboot(void *arg) { thread_sleep(250); platform_halt(HALT_ACTION_REBOOT, HALT_REASON_SW_RESET); return 0; }
/* Connection thread. Here we take clients off the connection queue and check * the contents provided. We set up the parser then hand off to the specific * request handler. */ static void *_handle_connection(void *arg) { http_parser_t *parser; char *rawuri, *uri; while (global.running == ICE_RUNNING) { kitsune_update("connection_handle"); /**DSU updatepoint */ client_queue_t *node = _get_connection(); if (node) { client_t *client = node->client; /* Check for special shoutcast compatability processing */ if (node->shoutcast) { _handle_shoutcast_compatible (node); continue; } /* process normal HTTP headers */ parser = httpp_create_parser(); httpp_initialize(parser, NULL); client->parser = parser; if (httpp_parse (parser, client->refbuf->data, node->offset)) { /* we may have more than just headers, so prepare for it */ if (node->stream_offset == node->offset) client->refbuf->len = 0; else { char *ptr = client->refbuf->data; client->refbuf->len = node->offset - node->stream_offset; memmove (ptr, ptr + node->stream_offset, client->refbuf->len); } free (node); if (strcmp("ICE", httpp_getvar(parser, HTTPP_VAR_PROTOCOL)) && strcmp("HTTP", httpp_getvar(parser, HTTPP_VAR_PROTOCOL))) { ERROR0("Bad HTTP protocol detected"); client_destroy (client); continue; } rawuri = httpp_getvar(parser, HTTPP_VAR_URI); uri = util_normalise_uri(rawuri); if (uri == NULL) { client_destroy (client); continue; } if (parser->req_type == httpp_req_source) { _handle_source_request (client, uri, ICECAST_SOURCE_AUTH); } else if (parser->req_type == httpp_req_stats) { _handle_stats_request (client, uri); } else if (parser->req_type == httpp_req_get) { _handle_get_request (client, uri); } else { ERROR0("Wrong request type from client"); client_send_400 (client, "unknown request"); } free(uri); } else { free (node); ERROR0("HTTP request parsing failed"); client_destroy (client); } continue; } thread_sleep (50000); } DEBUG0 ("Connection thread done"); return NULL; }
void * slave_comm_to_master (void * args) { master_node_t * my_master = (master_node_t *) args; net_thread_pool_t * net_thread_pool_node = NULL; int rc = 0; /* use pool node functionality */ net_thread_pool_node = malloc (sizeof (net_thread_pool_t)); net_thread_pool_node -> next = NULL; net_thread_pool_node -> net_thread_parameters.client_fd = -1; net_thread_pool_node -> net_thread_parameters.read_byte_size = 1500 - 160; /* Default MTU - header */ net_thread_pool_node -> net_thread_parameters.write_byte_size = 1500 - 160; /* Default MTU - header */ net_thread_pool_node -> net_thread_parameters.hostname = my_master -> master_node; net_thread_pool_node -> net_thread_parameters.net_thread_active_io_func = slave_comm_active_io; net_thread_pool_node -> net_thread_parameters.net_thread_idle_io_func = slave_comm_idle_io; net_thread_pool_node -> net_thread_parameters.net_thread_state_initiator_func = slave_comm_state_initiator; if (my_master -> password) net_thread_pool_node -> net_thread_parameters.net_thread_state_initiator_arg = strdup(my_master -> password); else net_thread_pool_node -> net_thread_parameters.net_thread_state_initiator_arg = NULL; net_thread_pool_node -> net_thread_parameters.net_thread_state_liberator_func = slave_comm_state_liberator; while (1) { if (!my_master) { scar_log (1, "%s: Error: no Master Node object set\n", __func__); return NULL; } /* pthread_cond_wait(&cv, &count_mutex); */ /* Fire up connection to home base */ scar_log (1, "%s: Connecting to \"%s\" on port \"%d\"\n", __func__, my_master -> master_node, my_master -> port); my_master -> socket = firstTCPSocketConnectingCorrectly (my_master -> master_node, my_master -> port); net_thread_pool_node -> net_thread_parameters.client_fd = my_master -> socket; if (my_master -> socket < 0) { scar_log (1, "%s: Error: unable to establish connection to the master node \"%s\" on port \"%d\"\n", __func__, my_master -> master_node, my_master -> port); } else { /* Re-use of code FTW! */ rc = pthread_create(&(net_thread_pool_node -> threadid), NULL, threadingDaemonClientHandler, (void*)(&net_thread_pool_node)); if (rc != 0) { scar_log (1, "%s: Failed to spawn thread.\n", __func__); } else { pthread_join (net_thread_pool_node -> threadid, NULL); } } /* Thread safe sleep */ scar_log (1, "Delay: 5 seconds before retry...\n"); thread_sleep(5); } return NULL; }
/* Most of the time we want to sleep for the same amount of time, defined in a constant, so we'll create a convenience function f or it. */ int thread_sleep_default() { return thread_sleep(TIME_OUT_SLEEP); }
int thread_wait_cond (void *event, dk_mutex_t *holds, TVAL timeout) { thread_sleep (timeout); return -1; }
DECLARE_TEST( event, delay_threaded ) { object_t thread[32]; producer_thread_arg_t args[32] = {0}; event_stream_t* stream; event_block_t* block; event_t* event; tick_t endtime, curtime, payloadtime, begintime, prevtime; unsigned int read[32]; int i; bool running = true; int num_threads = math_clamp( system_hardware_threads() * 4, 4, 32 ); stream = event_stream_allocate( 0 ); begintime = time_current(); for( i = 0; i < num_threads; ++i ) { args[i].stream = stream; args[i].end_time = time_current() + ( time_ticks_per_second() * 5 ); args[i].max_delay = time_ticks_per_second() * 5; args[i].sleep_time = 50; args[i].id = i; read[i] = 0; thread[i] = thread_create( producer_thread, "event_producer", THREAD_PRIORITY_NORMAL, 0 ); thread_start( thread[i], &args[i] ); } test_wait_for_threads_startup( thread, num_threads ); while( running ) { running = false; for( i = 0; i < num_threads; ++i ) { if( thread_is_running( thread[i] ) ) { running = true; break; } } thread_yield(); prevtime = begintime; begintime = time_current(); block = event_stream_process( stream ); event = event_next( block, 0 ); curtime = time_current(); while( event ) { running = true; ++read[ event->object ]; memcpy( &payloadtime, event->payload, sizeof( tick_t ) ); EXPECT_GE( event_payload_size( event ), 8 ); EXPECT_LE( event_payload_size( event ), 256 ); EXPECT_GE( payloadtime, prevtime ); EXPECT_GE( curtime, payloadtime ); event = event_next( block, event ); curtime = time_current(); } } endtime = time_current() + ( time_ticks_per_second() * 6 ); do { prevtime = begintime; begintime = time_current(); block = event_stream_process( stream ); event = event_next( block, 0 ); curtime = time_current(); while( event ) { ++read[ event->object ]; memcpy( &payloadtime, event->payload, sizeof( tick_t ) ); EXPECT_GE( event_payload_size( event ), 8 ); EXPECT_LE( event_payload_size( event ), 256 ); EXPECT_GE( payloadtime, prevtime ); EXPECT_GE( curtime, payloadtime ); event = event_next( block, event ); curtime = time_current(); } thread_sleep( 10 ); } while( time_current() < endtime ); for( i = 0; i < num_threads; ++i ) { unsigned int should_have_read = (unsigned int)((uintptr_t)thread_result( thread[i] )); EXPECT_EQ( read[i], should_have_read ); thread_terminate( thread[i] ); thread_destroy( thread[i] ); } test_wait_for_threads_exit( thread, num_threads ); event_stream_deallocate( stream ); return 0; }
void connection_accept_loop (void) { connection_t *con; ice_config_t *config; int duration = 300; config = config_get_config (); get_ssl_certificate (config); config_release_config (); while (global.running == ICE_RUNNING) { con = _accept_connection (duration); if (con) { client_queue_t *node; ice_config_t *config; client_t *client = NULL; listener_t *listener; global_lock(); if (client_create (&client, con, NULL) < 0) { global_unlock(); client_send_403 (client, "Icecast connection limit reached"); /* don't be too eager as this is an imposed hard limit */ thread_sleep (400000); continue; } /* setup client for reading incoming http */ client->refbuf->data [PER_CLIENT_REFBUF_SIZE-1] = '\000'; if (sock_set_blocking (client->con->sock, 0) || sock_set_nodelay (client->con->sock)) { global_unlock(); WARN0 ("failed to set tcp options on client connection, dropping"); client_destroy (client); continue; } node = calloc (1, sizeof (client_queue_t)); if (node == NULL) { global_unlock(); client_destroy (client); continue; } node->client = client; config = config_get_config(); listener = config_get_listen_sock (config, client->con); if (listener) { if (listener->shoutcast_compat) node->shoutcast = 1; if (listener->ssl && ssl_ok) connection_uses_ssl (client->con); if (listener->shoutcast_mount) node->shoutcast_mount = strdup (listener->shoutcast_mount); } global_unlock(); config_release_config(); _add_request_queue (node); stats_event_inc (NULL, "connections"); duration = 5; } else { if (_req_queue == NULL) duration = 300; /* use longer timeouts when nothing waiting */ } process_request_queue (); } /* Give all the other threads notification to shut down */ thread_cond_broadcast(&global.shutdown_cond); /* wait for all the sources to shutdown */ thread_rwlock_wlock(&_source_shutdown_rwlock); thread_rwlock_unlock(&_source_shutdown_rwlock); }
DECLARE_TEST( window, sizemove ) { window_t* window; #if FOUNDATION_PLATFORM_MACOSX window = window_allocate_from_nswindow( delegate_nswindow() ); #elif FOUNDATION_PLATFORM_IOS window = window_allocate_from_uiwindow( delegate_uiwindow() ); #endif EXPECT_NE( window, 0 ); EXPECT_TRUE( window_is_open( window ) ); thread_sleep( 1000 ); #if FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID EXPECT_TRUE( window_is_maximized( window ) ); #else EXPECT_FALSE( window_is_maximized( window ) ); #endif EXPECT_TRUE( window_is_visible( window ) ); EXPECT_TRUE( window_has_focus( window ) ); window_maximize( window ); thread_sleep( 1000 ); EXPECT_TRUE( window_is_maximized( window ) ); EXPECT_TRUE( window_has_focus( window ) ); #if !FOUNDATION_PLATFORM_IOS && !FOUNDATION_PLATFORM_ANDROID window_restore( window ); thread_sleep( 1000 ); EXPECT_FALSE( window_is_maximized( window ) ); EXPECT_TRUE( window_has_focus( window ) ); #endif window_maximize( window ); thread_sleep( 1000 ); EXPECT_TRUE( window_is_maximized( window ) ); #if !FOUNDATION_PLATFORM_IOS && !FOUNDATION_PLATFORM_ANDROID window_resize( window, 150, 100 ); thread_sleep( 1000 ); EXPECT_EQ( window_width( window ), 150 ); EXPECT_EQ( window_height( window ), 100 ); EXPECT_FALSE( window_is_maximized( window ) ); EXPECT_TRUE( window_has_focus( window ) ); window_move( window, 10, 20 ); thread_sleep( 1000 ); EXPECT_EQ( window_position_x( window ), 10 ); EXPECT_EQ( window_position_y( window ), 20 ); EXPECT_FALSE( window_is_maximized( window ) ); EXPECT_TRUE( window_has_focus( window ) ); window_minimize( window ); thread_sleep( 1000 ); EXPECT_FALSE( window_is_maximized( window ) ); EXPECT_FALSE( window_has_focus( window ) ); window_restore( window ); thread_sleep( 1000 ); EXPECT_FALSE( window_is_maximized( window ) ); EXPECT_FALSE( window_is_minimized( window ) ); EXPECT_TRUE( window_has_focus( window ) ); window_minimize( window ); thread_sleep( 1000 ); EXPECT_FALSE( window_is_maximized( window ) ); EXPECT_TRUE( window_is_minimized( window ) ); #endif window_deallocate( window ); window = 0; EXPECT_FALSE( window_is_open( window ) ); return 0; }
void ExeTask::cbackBy_Thrfunc() { bool isWin = false; m_iterCount = 0; m_running = true; m_joining = false; setCompleted(false); if(m_task != NULL){ std::string performFile = getNodeName(); if(TaskConfig::isloggingTimePeriod()) { PerformTable::init(); } #ifdef _WIN32 isWin = true; QueryPerformanceCounter(&liCounter0); #else struct timespec tp0, tp1, tp2; double litemp; clock_gettime(CLOCK_MONOTONIC, &tp0); #endif if(isWin && TaskConfig::isUsingQueueTimer()){ this->start_que(m_TimerQueue, getNodeName()); if(TaskConfig::isloggingTimePeriod()) performFile.append("-Timer"); } else{ //2. run while(1){ #ifdef _WIN32 QueryPerformanceFrequency(&liFrequency); // retrieves the frequency of the high-resolution performance counter QueryPerformanceCounter(&liCounter1); // Start litemp = (double)(liCounter1.QuadPart - liCounter0.QuadPart) / (double)liFrequency.QuadPart; liCounter0 = liCounter1; #else clock_gettime(CLOCK_MONOTONIC, &tp1); litemp = ((double)(tp1.tv_sec*1000) + (double)(tp1.tv_nsec)/1000000)-((double)(tp0.tv_sec*1000) + (double)(tp0.tv_nsec)/1000000); tp0.tv_sec = tp1.tv_sec; tp0.tv_nsec = tp1.tv_nsec; #endif if(m_stop){ //외부로 부터 쓰레드 중지 명령 break; } try{ if(m_runner->isDebugMode() && !m_isDbgCondCreated){ //디버깅인데 cond가 아직 생성이 안되면 아무것도 안한다. } else{ m_runner->enterTask(this, m_task); if(isCompleted()) break; } } catch(RuntimeEH& runEH){ //runEH.printError(); FLOG_ERROR(m_logFile, " (RUNNING:%d) 값을 획득하는데 실패하였습니다.", runEH.getErrorCode()); //return runEH.getErrorCode(); } FLOG_TRACE(m_logFile, " (RUNNING:CYCLE) This is the end of a cycle.\n"); m_iterCount++; #ifdef _WIN32 QueryPerformanceCounter(&liCounter2); PeRecord rec; rec.name = getInstanceName(); rec.cycle = litemp; rec.proc = (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart; //printf("<%s> Cycle Time : %f, Process Time : %f\n", getInstanceName().c_str(), litemp, (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart); #else clock_gettime(CLOCK_MONOTONIC, &tp2); PeRecord rec; rec.name = getInstanceName(); rec.cycle = litemp; rec.proc = ((double)(tp2.tv_sec*1000) + (double)(tp2.tv_nsec)/1000000)-((double)(tp1.tv_sec*1000) + (double)(tp1.tv_nsec)/1000000); #endif if(TaskConfig::isloggingTimePeriod()){ PerformTable::addPeRecord(rec); } float sleeptime = m_timePeriod - rec.proc*1000; if(sleeptime<0) sleeptime = 0; thread_sleep(sleeptime); //timespec a; //a.tv_sec = 0; //a.tv_nsec = 5000000 - rec.proc * 1000000; //nanosleep(&a, NULL); } if(TaskConfig::isloggingTimePeriod()) performFile.append("-Thread"); } m_runner->enterDestruct(this); m_running = false; if(TaskConfig::isloggingTimePeriod()) PerformTable::makeFile(performFile); } if(m_runner->isDebugMode()||m_runner->isMonitorMode()){ m_runner->delCondMu4BP(getThreadNum()); m_isDbgCondCreated = false; this->sendThreadInfo("delete"); //Task 쓰레드 delete가 전송되면 종료임을 알 수 있다. this->sendMonitorMsg("RES-EOT"); DbgTable::clearTable(); } }
/* get some data from the source. The stream data is placed in a refbuf * and sent back, however NULL is also valid as in the case of a short * timeout and there's no data pending. */ static refbuf_t *get_next_buffer (source_t *source) { refbuf_t *refbuf = NULL; int delay = 250; if (source->short_delay) delay = 0; while (global.running == ICE_RUNNING && source->running) { int fds = 0; time_t current = time (NULL); if (source->client) fds = util_timed_wait_for_fd (source->con->sock, delay); else { thread_sleep (delay*1000); source->last_read = current; } if (current >= source->client_stats_update) { stats_event_args (source->mount, "total_bytes_read", "%"PRIu64, source->format->read_bytes); stats_event_args (source->mount, "total_bytes_sent", "%"PRIu64, source->format->sent_bytes); source->client_stats_update = current + 5; } if (fds < 0) { if (! sock_recoverable (sock_error())) { WARN0 ("Error while waiting on socket, Disconnecting source"); source->running = 0; } break; } if (fds == 0) { if (source->last_read + (time_t)source->timeout < current) { DEBUG3 ("last %ld, timeout %d, now %ld", (long)source->last_read, source->timeout, (long)current); WARN0 ("Disconnecting source due to socket timeout"); source->running = 0; } break; } source->last_read = current; refbuf = source->format->get_buffer (source); if (source->client->con && source->client->con->error) { INFO1 ("End of Stream %s", source->mount); source->running = 0; continue; } if (refbuf) break; } return refbuf; }
int main_initialize(void) { foundation_config_t config; application_t application; int ret; size_t iarg, asize; const string_const_t* cmdline = environment_command_line(); _test_memory_tracker = true; for (iarg = 0, asize = array_size(cmdline); iarg < asize; ++iarg) { if (string_equal(STRING_ARGS(cmdline[iarg]), STRING_CONST("--no-memory-tracker"))) _test_memory_tracker = false; } if (_test_memory_tracker) memory_set_tracker(memory_tracker_local()); memset(&config, 0, sizeof(config)); #if BUILD_MONOLITHIC //For fs monitor test config.fs_monitor_max = 1; //For temporary allocator test, 256KiB config.temporary_memory = 256 * 1024; //For testing static hash store config.hash_store_size = 32 * 1024; //Test preallocation of random state buffers config.random_state_prealloc = 4; #endif memset(&application, 0, sizeof(application)); application.name = string_const(STRING_CONST("Foundation library test suite")); application.short_name = string_const(STRING_CONST("test_all")); application.company = string_const(STRING_CONST("Rampant Pixels")); application.version = foundation_version(); application.flags = APPLICATION_UTILITY; application.exception_handler = test_exception_handler; log_set_suppress(0, ERRORLEVEL_INFO); #if (FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID) && BUILD_ENABLE_LOG log_set_handler(test_log_handler); #endif #if !FOUNDATION_PLATFORM_IOS && !FOUNDATION_PLATFORM_ANDROID && !FOUNDATION_PLATFORM_PNACL _test_should_start = true; #endif ret = foundation_initialize(memory_system_malloc(), application, config); #if BUILD_MONOLITHIC //For monolithic process test if (string_array_find(cmdline, array_size(cmdline), STRING_CONST("wait for kill")) >= 0) { while (true) thread_sleep(100); } test_set_suitable_working_directory(); #endif return ret; }
void clock_tests(void) { uint32_t c; lk_time_t t; lk_bigtime_t t2; thread_sleep(100); c = arch_cycle_count(); t = current_time(); c = arch_cycle_count() - c; printf("%u cycles per current_time()\n", c); thread_sleep(100); c = arch_cycle_count(); t2 = current_time_hires(); c = arch_cycle_count() - c; printf("%u cycles per current_time_hires()\n", c); printf("making sure time never goes backwards\n"); { printf("testing current_time()\n"); lk_time_t start = current_time(); lk_time_t last = start; for (;;) { t = current_time(); //printf("%lu %lu\n", last, t); if (TIME_LT(t, last)) { printf("WARNING: time ran backwards: %lu < %lu\n", last, t); } last = t; if (last - start > 5000) break; } } { printf("testing current_time_hires()\n"); lk_bigtime_t start = current_time_hires(); lk_bigtime_t last = start; for (;;) { t2 = current_time_hires(); //printf("%llu %llu\n", last, t2); if (t2 < last) { printf("WARNING: time ran backwards: %llu < %llu\n", last, t2); } last = t2; if (last - start > 5000000) break; } } printf("making sure current_time() and current_time_hires() are always the same base\n"); { lk_time_t start = current_time(); for (;;) { t = current_time(); t2 = current_time_hires(); if (t > (t2 / 1000)) { printf("WARNING: current_time() ahead of current_time_hires() %lu %llu\n", t, t2); } if (t - start > 5000) break; } } printf("counting to 5, in one second intervals\n"); for (int i = 0; i < 5; i++) { thread_sleep(1000); printf("%d\n", i + 1); } printf("measuring cpu clock against current_time_hires()\n"); for (int i = 0; i < 5; i++) { uint cycles = arch_cycle_count(); lk_bigtime_t start = current_time_hires(); while ((current_time_hires() - start) < 1000000) ; cycles = arch_cycle_count() - cycles; printf("%u cycles per second\n", cycles); } }
int main_run(void* main_arg) { #if !BUILD_MONOLITHIC string_const_t pattern; string_t* exe_paths = 0; size_t iexe, exesize; process_t* process = 0; string_t process_path = { 0, 0 }; unsigned int* exe_flags = 0; #else void* test_result; #endif #if FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID || FOUNDATION_PLATFORM_PNACL int remain_counter = 0; #endif #if BUILD_DEBUG const string_const_t build_name = string_const(STRING_CONST("debug")); #elif BUILD_RELEASE const string_const_t build_name = string_const(STRING_CONST("release")); #elif BUILD_PROFILE const string_const_t build_name = string_const(STRING_CONST("profile")); #elif BUILD_DEPLOY const string_const_t build_name = string_const(STRING_CONST("deploy")); #endif #if BUILD_MONOLITHIC const string_const_t build_type = string_const(STRING_CONST(" monolithic")); #else const string_const_t build_type = string_empty(); #endif char* pathbuf; int process_result = 0; thread_t event_thread; FOUNDATION_UNUSED(main_arg); FOUNDATION_UNUSED(build_name); log_set_suppress(HASH_TEST, ERRORLEVEL_DEBUG); log_infof(HASH_TEST, STRING_CONST("Foundation library v%s built for %s using %s (%.*s%.*s)"), string_from_version_static(foundation_version()).str, FOUNDATION_PLATFORM_DESCRIPTION, FOUNDATION_COMPILER_DESCRIPTION, STRING_FORMAT(build_name), STRING_FORMAT(build_type)); thread_initialize(&event_thread, event_loop, 0, STRING_CONST("event_thread"), THREAD_PRIORITY_NORMAL, 0); thread_start(&event_thread); pathbuf = memory_allocate(HASH_STRING, BUILD_MAX_PATHLEN, 0, MEMORY_PERSISTENT); while (!thread_is_running(&event_thread)) thread_sleep(10); #if FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID || FOUNDATION_PLATFORM_PNACL while (!_test_should_start) { #if FOUNDATION_PLATFORM_ANDROID system_process_events(); #endif thread_sleep(100); } #endif fs_remove_directory(STRING_ARGS(environment_temporary_directory())); #if (FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID) && !BUILD_ENABLE_LOG test_log_view_append(STRING_CONST("Tests starting\n")); #endif #if BUILD_MONOLITHIC test_run_fn tests[] = { test_app_run, test_array_run, test_atomic_run, test_base64_run, test_beacon_run, test_bitbuffer_run, test_blowfish_run, test_bufferstream_run, test_exception_run, test_environment_run, test_error_run, test_event_run, test_fs_run, test_hash_run, test_hashmap_run, test_hashtable_run, test_json_run, test_library_run, test_math_run, test_md5_run, test_mutex_run, test_objectmap_run, test_path_run, test_pipe_run, test_process_run, test_profile_run, test_radixsort_run, test_random_run, test_regex_run, test_ringbuffer_run, test_semaphore_run, test_sha_run, test_stacktrace_run, test_stream_run, //stream test closes stdin test_string_run, test_system_run, test_time_run, test_uuid_run, 0 }; #if FOUNDATION_PLATFORM_ANDROID thread_t test_thread; thread_initialize(&test_thread, test_runner, tests, STRING_CONST("test_runner"), THREAD_PRIORITY_NORMAL, 0); thread_start(&test_thread); log_debug(HASH_TEST, STRING_CONST("Starting test runner thread")); while (!thread_is_started(&test_thread)) { system_process_events(); thread_sleep(100); } while (thread_is_running(&test_thread)) { system_process_events(); thread_sleep(100); } test_result = thread_join(&test_thread); process_result = (int)(intptr_t)test_result; thread_finalize(&test_thread); #else test_result = test_runner(tests); process_result = (int)(intptr_t)test_result; #endif if (process_result != 0) log_warnf(HASH_TEST, WARNING_SUSPICIOUS, STRING_CONST("Tests failed with exit code %d"), process_result); #if (FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID) && !BUILD_ENABLE_LOG if (process_result) test_log_view_append(STRING_CONST("Tests FAILED\n")); else test_log_view_append(STRING_CONST("Tests PASSED\n")); #endif #if FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID || FOUNDATION_PLATFORM_PNACL while (!_test_should_terminate && _test_have_focus && (remain_counter < 50)) { system_process_events(); thread_sleep(100); ++remain_counter; } #endif log_debug(HASH_TEST, STRING_CONST("Exiting main loop")); #else // !BUILD_MONOLITHIC //Find all test executables in the current executable directory #if FOUNDATION_PLATFORM_WINDOWS pattern = string_const(STRING_CONST("^test-.*\\.exe$")); #elif FOUNDATION_PLATFORM_MACOSX pattern = string_const(STRING_CONST("^test-.*$")); #elif FOUNDATION_PLATFORM_POSIX pattern = string_const(STRING_CONST("^test-.*$")); #else # error Not implemented #endif exe_paths = fs_matching_files(STRING_ARGS(environment_executable_directory()), STRING_ARGS(pattern), false); array_resize(exe_flags, array_size(exe_paths)); memset(exe_flags, 0, sizeof(unsigned int) * array_size(exe_flags)); #if FOUNDATION_PLATFORM_MACOSX //Also search for test applications string_const_t app_pattern = string_const(STRING_CONST("^test-.*\\.app$")); regex_t* app_regex = regex_compile(app_pattern.str, app_pattern.length); string_t* subdirs = fs_subdirs(STRING_ARGS(environment_executable_directory())); for (size_t idir = 0, dirsize = array_size(subdirs); idir < dirsize; ++idir) { if (regex_match(app_regex, subdirs[idir].str, subdirs[idir].length, 0, 0)) { string_t exe_path = string_clone(subdirs[idir].str, subdirs[idir].length - 4); array_push(exe_paths, exe_path); array_push(exe_flags, PROCESS_MACOSX_USE_OPENAPPLICATION); } } string_array_deallocate(subdirs); regex_deallocate(app_regex); #endif for (iexe = 0, exesize = array_size(exe_paths); iexe < exesize; ++iexe) { string_const_t* process_args = 0; string_const_t exe_file_name = path_base_file_name(STRING_ARGS(exe_paths[iexe])); if (string_equal(STRING_ARGS(exe_file_name), STRING_ARGS(environment_executable_name()))) continue; //Don't run self process_path = path_concat(pathbuf, BUILD_MAX_PATHLEN, STRING_ARGS(environment_executable_directory()), STRING_ARGS(exe_paths[iexe])); process = process_allocate(); process_set_executable_path(process, STRING_ARGS(process_path)); process_set_working_directory(process, STRING_ARGS(environment_executable_directory())); process_set_flags(process, PROCESS_ATTACHED | exe_flags[iexe]); if (!_test_memory_tracker) array_push(process_args, string_const(STRING_CONST("--no-memory-tracker"))); process_set_arguments(process, process_args, array_size(process_args)); log_infof(HASH_TEST, STRING_CONST("Running test executable: %.*s"), STRING_FORMAT(exe_paths[iexe])); process_result = process_spawn(process); while (process_result == PROCESS_WAIT_INTERRUPTED) { thread_sleep(10); process_result = process_wait(process); } process_deallocate(process); array_deallocate(process_args); if (process_result != 0) { #if (FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID) && !BUILD_ENABLE_LOG char buffer[64]; string_const_t msg = string_format(buffer, sizeof(buffer), "Test %.*s failed\n", STRING_FORMAT(exe_paths[iexe])); test_log_view_append(STRING_ARGS(msg)); #endif if (process_result >= PROCESS_INVALID_ARGS) log_warnf(HASH_TEST, WARNING_SUSPICIOUS, STRING_CONST("Tests failed, process terminated with error %x"), process_result); else log_warnf(HASH_TEST, WARNING_SUSPICIOUS, STRING_CONST("Tests failed with exit code %d"), process_result); process_set_exit_code(-1); goto exit; } #if (FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID) && !BUILD_ENABLE_LOG { char buffer[64]; string_const_t msg = string_format(buffer, sizeof(buffer), "Test %.*s PASSED\n", STRING_FORMAT(exe_paths[iexe])); test_log_view_append(STRING_ARGS(msg)); } #endif log_infof(HASH_TEST, STRING_CONST("All tests from %.*s passed (%d)"), STRING_FORMAT(exe_paths[iexe]), process_result); } log_info(HASH_TEST, STRING_CONST("All tests passed")); exit: if (exe_paths) string_array_deallocate(exe_paths); array_deallocate(exe_flags); #endif _test_should_terminate = true; thread_signal(&event_thread); thread_join(&event_thread); thread_finalize(&event_thread); memory_deallocate(pathbuf); log_infof(HASH_TEST, STRING_CONST("Tests exiting: %s (%d)"), process_result ? "FAILED" : "PASSED", process_result); if (process_result) memory_set_tracker(memory_tracker_none()); return process_result; }
int main(int argc, char *argv[], char *envp[]) { //start //no check ::signal(SIGTTOU, SIG_IGN); ::signal(SIGTTIN, SIG_IGN); ::signal(SIGTSTP, SIG_IGN); ::signal(SIGHUP, SIG_IGN); //fork pid_t pid = ::fork(); if( pid == -1 ) { ::perror("cannot fork!\n"); exit(EXIT_FAILURE); //return -1; } if( pid != 0 ) { exit(EXIT_SUCCESS); //parent process //return 0; } //in child //setsid pid = ::setsid(); if( pid == (pid_t)-1 ) { ::perror("cannot initialize session!\n"); return -1; } ::signal(SIGHUP, SIG_IGN); /* //second //fork pid_t pid2 = ::fork(); if( pid2 == -1 ) { ::perror("cannot fork 2!\n"); exit(EXIT_FAILURE); //return -1; } if( pid2 != 0 ) { exit(EXIT_SUCCESS); //parent process //return 0; } ::signal(SIGHUP, SIG_IGN); */ //cwd if( ::chdir("/") == -1 ) { ::perror("cannot change dir!\n"); return -1; } //close handles const int c_MAXFILE = 65535; for( int i = 0; i < c_MAXFILE; i ++ ) ::close(i); //no check //::open("/dev/null", O_RDONLY); //::open("/dev/null", O_RDWR); //::open("/dev/null", O_RDWR); //mask ::umask(0); //signal ::signal(SIGCHLD, SIG_IGN); //no check /* ::signal(SIGINT, SIG_IGN); //no check ::signal(SIGWINCH, SIG_IGN); //no check */ //command const_array<const_string_s> args; _auto_mem spArgs; //convert try { _cmdline_to_strings(argc, argv, spArgs, args); //may throw } catch(...) { report_service_log(GKC_SERVICE_NAME, SERVICE_LOG_ERROR, _S("Out of memory!")); return -1; } //arrange to catch the signal ::signal(SIGTERM, _sig_term); //no check //global //time time_initialize(); //loop report_service_log(GKC_SERVICE_NAME, SERVICE_LOG_SUCCESS, _S("Start Service!")); service_main_loop sml; if( !sml.Prepare(args) ) { report_service_log(GKC_SERVICE_NAME, SERVICE_LOG_ERROR, _S("Initialize loop failed!")); return -1; } while( !g_ServiceExitFlag ) { if( !sml.OneLoop() ) break; thread_sleep(1); } //end while //final int ret = sml.Cleanup(); report_service_log(GKC_SERVICE_NAME, SERVICE_LOG_SUCCESS, _S("Service Stopped!")); return ret; }
void CMain::JSONUpdateThread(void *pUser) { CJSONUpdateThreadData *m_pJSONUpdateThreadData = (CJSONUpdateThreadData *)pUser; CClient *pClients = m_pJSONUpdateThreadData->pClients; CConfig *pConfig = m_pJSONUpdateThreadData->pConfig; while(gs_Running) { char aFileBuf[2048*NET_MAX_CLIENTS]; char *pBuf = aFileBuf; str_format(pBuf, sizeof(aFileBuf), "{\n\"servers\": [\n"); pBuf += strlen(pBuf); for(int i = 0; i < NET_MAX_CLIENTS; i++) { if(!pClients[i].m_Active || pClients[i].m_Disabled) continue; if(pClients[i].m_Connected) { // Connectivity bool Online4; bool Online6; Online4 = pClients[i].m_Stats.m_Online4; Online6 = pClients[i].m_Stats.m_Online6; // Uptime char aUptime[16]; int Days = pClients[i].m_Stats.m_Uptime/60.0/60.0/24.0; if(Days > 0) { if(Days > 1) str_format(aUptime, sizeof(aUptime), "%d days", Days); else str_format(aUptime, sizeof(aUptime), "%d day", Days); } else str_format(aUptime, sizeof(aUptime), "%02d:%02d:%02d", (int)(pClients[i].m_Stats.m_Uptime/60.0/60.0), (int)((pClients[i].m_Stats.m_Uptime/60)%60), (int)((pClients[i].m_Stats.m_Uptime)%60)); // Load float Load = pClients[i].m_Stats.m_Load; // CPU int CPU = pClients[i].m_Stats.m_CPU; // Memory int Memory; if(pClients[i].m_Stats.m_MemTotal) Memory = round(((float)pClients[i].m_Stats.m_MemUsed/pClients[i].m_Stats.m_MemTotal)*100.0); else Memory = 0; // HDD int HDD; if(pClients[i].m_Stats.m_HDDTotal) HDD = round(((float)pClients[i].m_Stats.m_HDDUsed/pClients[i].m_Stats.m_HDDTotal)*100.0); else HDD = 0; str_format(pBuf, sizeof(aFileBuf) - (pBuf - aFileBuf), "{ \"name\": \"%s\", \"type\": \"%s\", \"host\": \"%s\", \"location\": \"%s\", \"online4\": %s, \"online6\": %s, \"uptime\": \"%s\", \"load\": \"%.2f\", \"network_rx\": %d, \"network_tx\": %d, \"cpu\": %d, \"memory\": %d, \"memory_total\": %" PRId64 ", \"memory_used\": %" PRId64 ", \"hdd\": %d, \"hdd_total\": %" PRId64 ", \"hdd_used\": %" PRId64 " },\n", pClients[i].m_aName, pClients[i].m_aType, pClients[i].m_aHost, pClients[i].m_aLocation, Online4 ? "true" : "false", Online6 ? "true" : "false", aUptime, Load, pClients[i].m_Stats.m_NetworkRx, pClients[i].m_Stats.m_NetworkTx, CPU, Memory, pClients[i].m_Stats.m_MemTotal, pClients[i].m_Stats.m_MemUsed, HDD, pClients[i].m_Stats.m_HDDTotal, pClients[i].m_Stats.m_HDDUsed); pBuf += strlen(pBuf); } else { str_format(pBuf, sizeof(aFileBuf) - (pBuf - aFileBuf), "{ \"name\": \"%s\", \"type\": \"%s\", \"host\": \"%s\", \"location\": \"%s\", \"online4\": false, \"online6\": false },\n", pClients[i].m_aName, pClients[i].m_aType, pClients[i].m_aHost, pClients[i].m_aLocation); pBuf += strlen(pBuf); } } if(!m_pJSONUpdateThreadData->m_ReloadRequired) str_format(pBuf - 2, sizeof(aFileBuf) - (pBuf - aFileBuf), "\n],\n\"updated\": \"%lld\"\n}", (long long)time(/*ago*/0)); else { str_format(pBuf - 2, sizeof(aFileBuf) - (pBuf - aFileBuf), "\n],\n\"updated\": \"%lld\",\n\"reload\": true\n}", (long long)time(/*ago*/0)); m_pJSONUpdateThreadData->m_ReloadRequired--; } pBuf += strlen(pBuf); char aJSONFileTmp[1024]; str_format(aJSONFileTmp, sizeof(aJSONFileTmp), "%s~", pConfig->m_aJSONFile); IOHANDLE File = io_open(aJSONFileTmp, IOFLAG_WRITE); if(!File) { dbg_msg("main", "Couldn't open %s", aJSONFileTmp); exit(1); } io_write(File, aFileBuf, (pBuf - aFileBuf)); io_flush(File); io_close(File); fs_rename(aJSONFileTmp, pConfig->m_aJSONFile); thread_sleep(1000); } fs_remove(pConfig->m_aJSONFile); }
DECLARE_TEST( ringbufferstream, threadedio ) { ringbufferstream_test_t test = {0}; uint32_t* srcbuffer; unsigned int si; unsigned int loop, loops; real elapsed, throughput; unsigned int mbytes; #if FOUNDATION_PLATFORM_ANDROID || FOUNDATION_PLATFORM_IOS mbytes = 16; loops = 32; #else mbytes = 256; loops = 16; #endif test.buffer_size = mbytes * 1024 * 1024; srcbuffer = memory_allocate( test.buffer_size, 0, MEMORY_PERSISTENT ); test.source_buffer = (void*)srcbuffer; test.dest_buffer = memory_allocate_zero( test.buffer_size, 0, MEMORY_PERSISTENT ); for( si = 0; si < ( test.buffer_size / 4 ); ++si ) srcbuffer[si] = random32(); elapsed = 0; for( loop = 0; loop < loops; ++loop ) { test.stream = ringbuffer_stream_allocate( 23477, test.buffer_size ); test.read_thread = thread_create( read_thread, "reader", THREAD_PRIORITY_NORMAL, 0 ); test.write_thread = thread_create( write_thread, "writer", THREAD_PRIORITY_NORMAL, 0 ); thread_start( test.read_thread, &test ); thread_start( test.write_thread, &test ); thread_sleep( 100 ); while( thread_is_running( test.read_thread ) || thread_is_running( test.write_thread ) ) thread_sleep( 10 ); thread_destroy( test.read_thread ); thread_destroy( test.write_thread ); for( si = 0; si < test.buffer_size; ++si ) EXPECT_EQ( test.source_buffer[si], test.dest_buffer[si] ); stream_deallocate( test.stream ); elapsed += time_ticks_to_seconds( time_diff( test.start_time, test.end_time ) ); } throughput = (real)( (float64_t)( mbytes * loops ) / (float64_t)elapsed ); log_infof( HASH_TEST, "Ringbuffer throughput: %d MiB in %.2f sec -> %.2f MiB/sec", ( loops * mbytes ), (float32_t)elapsed, (float32_t)throughput ); elapsed = 0; for( loop = 0; loop < loops; ++loop ) { test.start_time = time_current(); memcpy( test.dest_buffer, test.source_buffer, test.buffer_size ); test.end_time = time_current(); for( si = 0; si < test.buffer_size; ++si ) EXPECT_EQ( test.source_buffer[si], test.dest_buffer[si] ); elapsed += time_ticks_to_seconds( time_diff( test.start_time, test.end_time ) ); } throughput = (real)( (float64_t)( mbytes * loops ) / (float64_t)elapsed ); log_infof( HASH_TEST, "Memcpy throughput: %d MiB in %.2f sec -> %.2f MiB/sec", ( loops * mbytes ), (float32_t)elapsed, (float32_t)throughput ); memory_deallocate( test.source_buffer ); memory_deallocate( test.dest_buffer ); return 0; }
static int do_ramboot(void *arg) { thread_sleep(250); arch_chain_load(lkb_iobuffer); return 0; }
static void *_stats_thread(void *arg) { stats_event_t *event; stats_event_t *copy; event_listener_t *listener; stats_event_time (NULL, "server_start"); stats_event_time_iso8601 (NULL, "server_start_iso8601"); /* global currently active stats */ stats_event (NULL, "clients", "0"); stats_event (NULL, "connections", "0"); stats_event (NULL, "sources", "0"); stats_event (NULL, "stats", "0"); stats_event (NULL, "listeners", "0"); /* global accumulating stats */ stats_event (NULL, "client_connections", "0"); stats_event (NULL, "source_client_connections", "0"); stats_event (NULL, "source_relay_connections", "0"); stats_event (NULL, "source_total_connections", "0"); stats_event (NULL, "stats_connections", "0"); stats_event (NULL, "listener_connections", "0"); ICECAST_LOG_INFO("stats thread started"); while (_stats_running) { thread_mutex_lock(&_global_event_mutex); if (_global_event_queue.head != NULL) { /* grab the next event from the queue */ event = _get_event_from_queue (&_global_event_queue); thread_mutex_unlock(&_global_event_mutex); if (event == NULL) continue; event->next = NULL; thread_mutex_lock(&_stats_mutex); /* check if we are dealing with a global or source event */ if (event->source == NULL) process_global_event (event); else process_source_event (event); /* now we have an event that's been processed into the running stats */ /* this event should get copied to event listeners' queues */ listener = (event_listener_t *)_event_listeners; while (listener) { copy = _copy_event(event); thread_mutex_lock (&listener->mutex); _add_event_to_queue (copy, &listener->queue); thread_mutex_unlock (&listener->mutex); listener = listener->next; } /* now we need to destroy the event */ _free_event(event); thread_mutex_unlock(&_stats_mutex); continue; } else { thread_mutex_unlock(&_global_event_mutex); } thread_sleep(300000); } return NULL; }
void acpu_clock_init(void) { uint32_t i, clk; uint32_t val; uint32_t *clk_cntl_reg_val, size; unsigned msm_id, msm_version; msm_version = board_msm_version(); if (msm_version == 2) vdd_plevel = 4; else vdd_plevel = 6; /* Set VDD plevel */ writel((1 << 7) | (vdd_plevel << 3), VDD_SVS_PLEVEL_ADDR); #if (!ENABLE_NANDWRITE) thread_sleep(1); #else mdelay(1); #endif msm_id = board_msm_id(); switch (msm_id) { case MSM7227A: case MSM7627A: case ESM7227A: clk_cntl_reg_val = clk_cntl_reg_val_7627A; size = ARRAY_SIZE(clk_cntl_reg_val_7627A); pll_request(2, 1); /* TODO: Enable this PLL while switching to 800MHz */ #if 0 pll_request(4, 1); #endif break; case MSM8625: /* Fix me: Will move to PLL4 later */ clk_cntl_reg_val = clk_cntl_reg_val_7627A; size = ARRAY_SIZE(clk_cntl_reg_val_7627A); pll_request(2, 1); break; case MSM7225A: case MSM7625A: default: clk_cntl_reg_val = clk_cntl_reg_val_7625A; size = ARRAY_SIZE(clk_cntl_reg_val_7625A); pll_request(2, 1); break; }; /* Read clock source select bit. */ val = readl(A11S_CLK_SEL_ADDR); i = val & 1; /* Jump into table and set every entry. */ for (; i < size; i++) { val = readl(A11S_CLK_SEL_ADDR); val |= BIT(1) | BIT(2); writel(val, A11S_CLK_SEL_ADDR); val = readl(A11S_CLK_CNTL_ADDR); /* Make sure not to disturb already used src */ val &= clk_cntl_mask[i % 2]; val += clk_cntl_reg_val[i]; writel(val, A11S_CLK_CNTL_ADDR); /* Would need a dmb() here but the whole address space is * strongly ordered, so it should be fine. */ val = readl(A11S_CLK_SEL_ADDR); val &= ~(A11S_CLK_SEL_MASK); val |= (A11S_CLK_SEL_MASK & clk_sel_reg_val[i % 2]); writel(val, A11S_CLK_SEL_ADDR); #if (!ENABLE_NANDWRITE) thread_sleep(1); #else mdelay(1); #endif } }
/* システムコールの呼び出し */ static void call_functions(kz_syscall_type_t type, kz_syscall_param_t *p) { /* システムコールの実行中にcurrentが書き換わるので注意 */ switch (type) { /* kz_run() */ case KZ_SYSCALL_TYPE_RUN: p->un.run.ret = thread_run(p->un.run.func, p->un.run.name, p->un.run.priority, p->un.run.stacksize, p->un.run.argc, p->un.run.argv); break; /* kz_exit() */ case KZ_SYSCALL_TYPE_EXIT: thread_exit(); break; /* kz_wait() */ case KZ_SYSCALL_TYPE_WAIT: p->un.wait.ret = thread_wait(); break; /* kz_sleep() */ case KZ_SYSCALL_TYPE_SLEEP: p->un.sleep.ret = thread_sleep(); break; /* kz_wakeup() */ case KZ_SYSCALL_TYPE_WAKEUP: p->un.wakeup.ret = thread_wakeup(p->un.wakeup.id); break; /* kz_getid() */ case KZ_SYSCALL_TYPE_GETID: p->un.getid.ret = thread_getid(); break; /* kz_chpri() */ case KZ_SYSCALL_TYPE_CHPRI: p->un.chpri.ret = thread_chpri(p->un.chpri.priority); break; /* kz_kmalloc() */ case KZ_SYSCALL_TYPE_KMALLOC: p->un.kmalloc.ret = thread_kmalloc(p->un.kmalloc.size); break; /* kz_kmfree() */ case KZ_SYSCALL_TYPE_KMFREE: p->un.kmfree.ret = thread_kmfree(p->un.kmfree.p); break; /* kz_send() */ case KZ_SYSCALL_TYPE_SEND: p->un.send.ret = thread_send(p->un.send.id, p->un.send.size, p->un.send.p); break; /* kz_recv() */ case KZ_SYSCALL_TYPE_RECV: p->un.recv.ret = thread_recv(p->un.recv.id, p->un.recv.sizep, p->un.recv.pp); break; /* kz_setintr() */ case KZ_SYSCALL_TYPE_SETINTR: p->un.setintr.ret = thread_setintr(p->un.setintr.type, p->un.setintr.handler); break; default: break; } }
void connection_accept_loop(void) { connection_t *con; ice_config_t *config; config = config_get_config (); get_ssl_certificate (config); config_release_config (); tid = thread_create ("connection thread", _handle_connection, NULL, THREAD_ATTACHED); while (global.running == ICE_RUNNING) { con = _accept_connection(); if (con) { client_queue_t *node; ice_config_t *config; client_t *client = NULL; listener_t *listener; global_lock(); if (client_create (&client, con, NULL) < 0) { global_unlock(); client_send_403 (client, "Icecast connection limit reached"); /* don't be too eager as this is an imposed hard limit */ thread_sleep (400000); continue; } global_unlock(); /* setup client for reading incoming http */ client->refbuf->data [PER_CLIENT_REFBUF_SIZE-1] = '\000'; node = calloc (1, sizeof (client_queue_t)); if (node == NULL) { client_destroy (client); continue; } node->client = client; config = config_get_config(); listener = config_get_listen_sock (config, client->con); if (listener) { if (listener->shoutcast_compat) node->shoutcast = 1; if (listener->ssl && ssl_ok) connection_uses_ssl (client->con); if (listener->shoutcast_mount) node->shoutcast_mount = strdup (listener->shoutcast_mount); } config_release_config(); sock_set_blocking (client->con->sock, SOCK_NONBLOCK); sock_set_nodelay (client->con->sock); _add_request_queue (node); stats_event_inc (NULL, "connections"); } process_request_queue (); } /* Give all the other threads notification to shut down */ thread_cond_broadcast(&global.shutdown_cond); if (tid) thread_join (tid); /* wait for all the sources to shutdown */ thread_rwlock_wlock(&_source_shutdown_rwlock); thread_rwlock_unlock(&_source_shutdown_rwlock); }
static THREAD_FUNCTION thread_encoding_proc(void *p_data) { int ithread = ((ENCODETHREAD_DATA *)p_data)->ithread; VP8_COMP *cpi = (VP8_COMP *)(((ENCODETHREAD_DATA *)p_data)->ptr1); MB_ROW_COMP *mbri = (MB_ROW_COMP *)(((ENCODETHREAD_DATA *)p_data)->ptr2); ENTROPY_CONTEXT_PLANES mb_row_left_context; const int nsync = cpi->mt_sync_range; //printf("Started thread %d\n", ithread); while (1) { if (cpi->b_multi_threaded == 0) break; //if(WaitForSingleObject(cpi->h_event_mbrencoding[ithread], INFINITE) == WAIT_OBJECT_0) if (sem_wait(&cpi->h_event_start_encoding[ithread]) == 0) { VP8_COMMON *cm = &cpi->common; int mb_row; MACROBLOCK *x = &mbri->mb; MACROBLOCKD *xd = &x->e_mbd; TOKENEXTRA *tp ; int *segment_counts = mbri->segment_counts; int *totalrate = &mbri->totalrate; if (cpi->b_multi_threaded == 0) // we're shutting down break; for (mb_row = ithread + 1; mb_row < cm->mb_rows; mb_row += (cpi->encoding_thread_count + 1)) { int recon_yoffset, recon_uvoffset; int mb_col; int ref_fb_idx = cm->lst_fb_idx; int dst_fb_idx = cm->new_fb_idx; int recon_y_stride = cm->yv12_fb[ref_fb_idx].y_stride; int recon_uv_stride = cm->yv12_fb[ref_fb_idx].uv_stride; int map_index = (mb_row * cm->mb_cols); volatile int *last_row_current_mb_col; tp = cpi->tok + (mb_row * (cm->mb_cols * 16 * 24)); last_row_current_mb_col = &cpi->mt_current_mb_col[mb_row - 1]; // reset above block coeffs xd->above_context = cm->above_context; xd->left_context = &mb_row_left_context; vp8_zero(mb_row_left_context); xd->up_available = (mb_row != 0); recon_yoffset = (mb_row * recon_y_stride * 16); recon_uvoffset = (mb_row * recon_uv_stride * 8); cpi->tplist[mb_row].start = tp; //printf("Thread mb_row = %d\n", mb_row); // Set the mb activity pointer to the start of the row. x->mb_activity_ptr = &cpi->mb_activity_map[map_index]; // for each macroblock col in image for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) { if ((mb_col & (nsync - 1)) == 0) { while (mb_col > (*last_row_current_mb_col - nsync) && *last_row_current_mb_col != cm->mb_cols - 1) { x86_pause_hint(); thread_sleep(0); } } // Distance of Mb to the various image edges. // These specified to 8th pel as they are always compared to values that are in 1/8th pel units xd->mb_to_left_edge = -((mb_col * 16) << 3); xd->mb_to_right_edge = ((cm->mb_cols - 1 - mb_col) * 16) << 3; xd->mb_to_top_edge = -((mb_row * 16) << 3); xd->mb_to_bottom_edge = ((cm->mb_rows - 1 - mb_row) * 16) << 3; // Set up limit values for motion vectors used to prevent them extending outside the UMV borders x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16)); x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + (VP8BORDERINPIXELS - 16); x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16)); x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16) + (VP8BORDERINPIXELS - 16); xd->dst.y_buffer = cm->yv12_fb[dst_fb_idx].y_buffer + recon_yoffset; xd->dst.u_buffer = cm->yv12_fb[dst_fb_idx].u_buffer + recon_uvoffset; xd->dst.v_buffer = cm->yv12_fb[dst_fb_idx].v_buffer + recon_uvoffset; xd->left_available = (mb_col != 0); x->rddiv = cpi->RDDIV; x->rdmult = cpi->RDMULT; //Copy current mb to a buffer vp8_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16); if (cpi->oxcf.tuning == VP8_TUNE_SSIM) vp8_activity_masking(cpi, x); // Is segmentation enabled // MB level adjutment to quantizer if (xd->segmentation_enabled) { // Code to set segment id in xd->mbmi.segment_id for current MB (with range checking) if (cpi->segmentation_map[map_index + mb_col] <= 3) xd->mode_info_context->mbmi.segment_id = cpi->segmentation_map[map_index + mb_col]; else xd->mode_info_context->mbmi.segment_id = 0; vp8cx_mb_init_quantizer(cpi, x, 1); } else xd->mode_info_context->mbmi.segment_id = 0; // Set to Segment 0 by default x->active_ptr = cpi->active_map + map_index + mb_col; if (cm->frame_type == KEY_FRAME) { *totalrate += vp8cx_encode_intra_macro_block(cpi, x, &tp); #ifdef MODE_STATS y_modes[xd->mbmi.mode] ++; #endif } else { *totalrate += vp8cx_encode_inter_macroblock(cpi, x, &tp, recon_yoffset, recon_uvoffset); #ifdef MODE_STATS inter_y_modes[xd->mbmi.mode] ++; if (xd->mbmi.mode == SPLITMV) { int b; for (b = 0; b < xd->mbmi.partition_count; b++) { inter_b_modes[x->partition->bmi[b].mode] ++; } } #endif // Count of last ref frame 0,0 useage if ((xd->mode_info_context->mbmi.mode == ZEROMV) && (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME)) cpi->inter_zz_count++; // Special case code for cyclic refresh // If cyclic update enabled then copy xd->mbmi.segment_id; (which may have been updated based on mode // during vp8cx_encode_inter_macroblock()) back into the global sgmentation map if (cpi->cyclic_refresh_mode_enabled && xd->segmentation_enabled) { const MB_MODE_INFO * mbmi = &xd->mode_info_context->mbmi; cpi->segmentation_map[map_index + mb_col] = mbmi->segment_id; // If the block has been refreshed mark it as clean (the magnitude of the -ve influences how long it will be before we consider another refresh): // Else if it was coded (last frame 0,0) and has not already been refreshed then mark it as a candidate for cleanup next time (marked 0) // else mark it as dirty (1). if (mbmi->segment_id) cpi->cyclic_refresh_map[map_index + mb_col] = -1; else if ((mbmi->mode == ZEROMV) && (mbmi->ref_frame == LAST_FRAME)) { if (cpi->cyclic_refresh_map[map_index + mb_col] == 1) cpi->cyclic_refresh_map[map_index + mb_col] = 0; } else cpi->cyclic_refresh_map[map_index + mb_col] = 1; } } cpi->tplist[mb_row].stop = tp; // Increment pointer into gf useage flags structure. x->gf_active_ptr++; // Increment the activity mask pointers. x->mb_activity_ptr++; // adjust to the next column of macroblocks x->src.y_buffer += 16; x->src.u_buffer += 8; x->src.v_buffer += 8; recon_yoffset += 16; recon_uvoffset += 8; // Keep track of segment useage segment_counts[xd->mode_info_context->mbmi.segment_id]++; // skip to next mb xd->mode_info_context++; x->partition_info++; xd->above_context++; cpi->mt_current_mb_col[mb_row] = mb_col; } //extend the recon for intra prediction vp8_extend_mb_row( &cm->yv12_fb[dst_fb_idx], xd->dst.y_buffer + 16, xd->dst.u_buffer + 8, xd->dst.v_buffer + 8); // this is to account for the border xd->mode_info_context++; x->partition_info++; x->src.y_buffer += 16 * x->src.y_stride * (cpi->encoding_thread_count + 1) - 16 * cm->mb_cols; x->src.u_buffer += 8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) - 8 * cm->mb_cols; x->src.v_buffer += 8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) - 8 * cm->mb_cols; xd->mode_info_context += xd->mode_info_stride * cpi->encoding_thread_count; x->partition_info += xd->mode_info_stride * cpi->encoding_thread_count; x->gf_active_ptr += cm->mb_cols * cpi->encoding_thread_count; if (mb_row == cm->mb_rows - 1) { //SetEvent(cpi->h_event_main); sem_post(&cpi->h_event_end_encoding); /* signal frame encoding end */ } } } } //printf("exit thread %d\n", ithread); return 0; }
//============================================================================== int IVSS_Interface_XSpace_Simulation(IVSS_SYSTEM* system, IVSS_SIMULATOR* simulator, IVSS_UNIT* unit) { if (unit->type == IVSS_TYPE_XSPACE_VIDEO) { #ifdef FFMPEG_SUPPORT IVSS_VARIABLE* variable; unsigned char out_buf[128000]; int size, out_size, i; IVSS_Unit_GetNode(system,unit,"VideoSignal",&variable); /*int i, out_size, size, x, y, outbuf_size; FILE *f; uint8_t *outbuf, *picture_buf; //double error_probability = 0.0; printf("Video encoding\n");*/ //First-time initialization (FIXME) if ((!av_codec) && (!av_context)) { av_codec = avcodec_find_encoder(CODEC_ID_MPEG1VIDEO); av_context = avcodec_alloc_context(); av_picture = avcodec_alloc_frame(); av_context->bit_rate = 100000; av_context->width = 352; av_context->height = 288; av_context->time_base.den = 25; //25 FPS av_context->time_base.num = 1; av_context->gop_size = 10; //I-frame period av_context->max_b_frames = 1; av_context->pix_fmt = PIX_FMT_YUV420P; if (avcodec_open(av_context, av_codec) < 0) { av_codec = 0; } size = av_context->width * av_context->height; av_picture->data[0] = av_picture_yuv; av_picture->data[1] = av_picture->data[0] + size; av_picture->data[2] = av_picture->data[1] + size / 4; av_picture->linesize[0] = av_context->width; av_picture->linesize[1] = av_context->width / 2; av_picture->linesize[2] = av_context->width / 2; } if (av_codec && (!system->is_paused)) { int x,y; //Convert frame to YUV //Y = (0.257 * R) + (0.504 * G) + (0.098 * B) + 16 //Cr = V = (0.439 * R) - (0.368 * G) - (0.071 * B) + 128 //Cb = U = -(0.148 * R) - (0.291 * G) + (0.439 * B) + 128 //Y for(y = 0; y < av_context->height; y++) { for(x = 0; x < av_context->width; x++) { av_picture->data[0][y * av_picture->linesize[0] + x] = 16 +0.257*av_picture_data[(y*352+x)*3+0] +0.504*av_picture_data[(y*352+x)*3+1] +0.098*av_picture_data[(y*352+x)*3+2];//+x+y*2; } } //Cb and Cr for(y = 0; y < av_context->height/2; y++) { for(x = 0; x < av_context->width/2; x++) { av_picture->data[1][y * av_picture->linesize[1] + x] = 128 +0.439*av_picture_data[(2*y*352+2*x)*3+0]+ -0.368*av_picture_data[(2*y*352+2*x)*3+1]+ -0.071*av_picture_data[(2*y*352+2*x)*3+2]; av_picture->data[2][y * av_picture->linesize[2] + x] = 128 -0.148*av_picture_data[(2*y*352+2*x)*3+0] -0.291*av_picture_data[(2*y*352+2*x)*3+1] +0.439*av_picture_data[(2*y*352+2*x)*3+2]; } } //Encode current frame out_size = avcodec_encode_video(av_context, out_buf, 128000, av_picture); for (i = 0; i < out_size; i++) IVSS_Variable_WriteBuffer(system,variable,out_buf[i]); //Encode delayed frames while (out_size) { out_size = avcodec_encode_video(av_context, out_buf, 128000, 0); for (i = 0; i < out_size; i++) IVSS_Variable_WriteBuffer(system,variable,out_buf[i]); } } /*avcodec_close(c); av_free(c); av_free(picture);*/ thread_sleep(1.0/60.0); #endif } else { thread_sleep(1000.0); } return IVSS_OK; }
int process_spawn( process_t* proc ) { static char unescaped[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.:/\\"; int i, num_args; int size; #if FOUNDATION_PLATFORM_WINDOWS wchar_t* wcmdline; wchar_t* wwd; char* cmdline = 0; #endif if( !proc ) return PROCESS_INVALID_ARGS; proc->code = PROCESS_INVALID_ARGS; if( !string_length( proc->path ) ) return proc->code; //Always escape path on Windows platforms #if FOUNDATION_PLATFORM_POSIX if( string_find_first_not_of( proc->path, unescaped, 0 ) != STRING_NPOS ) #endif { if( proc->path[0] != '"' ) proc->path = string_prepend( proc->path, "\"" ); if( proc->path[ string_length( proc->path ) - 1 ] != '"' ) proc->path = string_append( proc->path, "\"" ); } size = array_size( proc->args ); for( i = 0, num_args = 0; i < size; ++i ) { char* arg = proc->args[i]; if( !string_length( arg ) ) continue; ++num_args; if( string_find_first_not_of( arg, unescaped, 0 ) != STRING_NPOS ) { if( arg[0] != '"' ) { //Check if we need to escape " characters unsigned int pos = string_find( arg, '"', 0 ); while( pos != STRING_NPOS ) { if( arg[ pos - 1 ] != '\\' ) { char* escarg = string_substr( arg, 0, pos ); char* left = string_substr( arg, pos, STRING_NPOS ); escarg = string_append( escarg, "\\" ); escarg = string_append( escarg, left ); string_deallocate( left ); string_deallocate( arg ); arg = escarg; } pos = string_find( arg, '"', pos + 2 ); } arg = string_prepend( arg, "\"" ); arg = string_append( arg, "\"" ); proc->args[i] = arg; } } } #if FOUNDATION_PLATFORM_WINDOWS # ifndef SEE_MASK_NOASYNC # define SEE_MASK_NOASYNC 0x00000100 # endif if( !( proc->flags & PROCESS_WINDOWS_USE_SHELLEXECUTE ) ) //Don't prepend exe path to parameters if using ShellExecute cmdline = string_clone( proc->path ); //Build command line string for( i = 0; i < size; ++i ) { char* arg = proc->args[i]; if( !string_length( arg ) ) continue; if( cmdline ) cmdline = string_append( cmdline, " " ); cmdline = string_append( cmdline, arg ); } if( !string_length( proc->wd ) ) proc->wd = string_clone( environment_current_working_directory() ); wcmdline = wstring_allocate_from_string( cmdline, 0 ); wwd = wstring_allocate_from_string( proc->wd, 0 ); if( proc->flags & PROCESS_WINDOWS_USE_SHELLEXECUTE ) { SHELLEXECUTEINFOW sei; wchar_t* wverb; wchar_t* wpath; wverb = ( proc->verb && string_length( proc->verb ) ) ? wstring_allocate_from_string( proc->verb, 0 ) : 0; wpath = wstring_allocate_from_string( proc->path, 0 ); ZeroMemory( &sei, sizeof( sei ) ); sei.cbSize = sizeof(SHELLEXECUTEINFOW); sei.hwnd = 0; sei.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI | SEE_MASK_NOCLOSEPROCESS; sei.lpVerb = wverb; sei.lpFile = wpath; sei.lpParameters = wcmdline; sei.lpDirectory = wwd; sei.nShow = SW_SHOWNORMAL; if( !( proc->flags & PROCESS_CONSOLE ) ) sei.fMask |= SEE_MASK_NO_CONSOLE; if( proc->flags & PROCESS_STDSTREAMS ) log_warnf( 0, WARNING_UNSUPPORTED, "Unable to redirect standard in/out through pipes when using ShellExecute for process spawning" ); log_debugf( 0, "Spawn process (ShellExecute): %s %s", proc->path, cmdline ); if( !ShellExecuteExW( &sei ) ) { log_warnf( 0, WARNING_SYSTEM_CALL_FAIL, "Unable to spawn process (ShellExecute) for executable '%s': %s", proc->path, system_error_message( GetLastError() ) ); } else { proc->hp = sei.hProcess; proc->ht = 0; proc->code = 0; } wstring_deallocate( wverb ); wstring_deallocate( wpath ); } else { STARTUPINFOW si; PROCESS_INFORMATION pi; BOOL inherit_handles = FALSE; memset( &si, 0, sizeof( si ) ); memset( &pi, 0, sizeof( pi ) ); si.cb = sizeof( si ); if( proc->flags & PROCESS_STDSTREAMS ) { proc->pipeout = pipe_allocate(); proc->pipein = pipe_allocate(); si.dwFlags |= STARTF_USESTDHANDLES; si.hStdOutput = pipe_write_handle( proc->pipeout ); si.hStdError = pipe_write_handle( proc->pipeout ); si.hStdInput = pipe_read_handle( proc->pipein ); //Don't inherit wrong ends of pipes SetHandleInformation( pipe_read_handle( proc->pipeout ), HANDLE_FLAG_INHERIT, 0 ); SetHandleInformation( pipe_write_handle( proc->pipein ), HANDLE_FLAG_INHERIT, 0 ); inherit_handles = TRUE; } log_debugf( 0, "Spawn process (CreateProcess): %s %s", proc->path, cmdline ); if( !CreateProcessW( 0/*wpath*/, wcmdline, 0, 0, inherit_handles, ( proc->flags & PROCESS_CONSOLE ) ? CREATE_NEW_CONSOLE : 0, 0, wwd, &si, &pi ) ) { log_warnf( 0, WARNING_SYSTEM_CALL_FAIL, "Unable to spawn process (CreateProcess) for executable '%s': %s", proc->path, system_error_message( GetLastError() ) ); stream_deallocate( proc->pipeout ); stream_deallocate( proc->pipein ); proc->pipeout = 0; proc->pipein = 0; } else { proc->hp = pi.hProcess; proc->ht = pi.hThread; proc->code = 0; } if( proc->pipeout ) pipe_close_write( proc->pipeout ); if( proc->pipein ) pipe_close_read( proc->pipein ); } wstring_deallocate( wcmdline ); wstring_deallocate( wwd ); string_deallocate( cmdline ); if( proc->code < 0 ) return proc->code; //Error #endif #if FOUNDATION_PLATFORM_MACOSX if( proc->flags & PROCESS_OSX_USE_OPENAPPLICATION ) { proc->pid = 0; LSApplicationParameters params; ProcessSerialNumber psn; FSRef* fsref = memory_allocate_zero( sizeof( FSRef ), 0, MEMORY_TEMPORARY ); memset( ¶ms, 0, sizeof( LSApplicationParameters ) ); memset( &psn, 0, sizeof( ProcessSerialNumber ) ); char* pathstripped = string_strip( string_clone( proc->path ), "\"" ); OSStatus status = 0; status = FSPathMakeRef( (uint8_t*)pathstripped, fsref, 0 ); if( status < 0 ) { pathstripped = string_append( pathstripped, ".app" ); status = FSPathMakeRef( (uint8_t*)pathstripped, fsref, 0 ); } CFStringRef* args = 0; for( i = 0, size = array_size( proc->args ); i < size; ++i ) //App gets executable path automatically, don't include array_push( args, CFStringCreateWithCString( 0, proc->args[i], kCFStringEncodingUTF8 ) ); CFArrayRef argvref = CFArrayCreate( 0, (const void**)args, (CFIndex)array_size( args ), 0 ); params.flags = kLSLaunchDefaults; params.application = fsref; params.argv = argvref; log_debugf( 0, "Spawn process (LSOpenApplication): %s", pathstripped ); status = LSOpenApplication( ¶ms, &psn ); if( status != 0 ) { proc->code = status; log_warnf( 0, WARNING_BAD_DATA, "Unable to spawn process for executable '%s': %s", proc->path, system_error_message( status ) ); } CFRelease( argvref ); for( i = 0, size = array_size( args ); i < size; ++i ) CFRelease( args[i] ); memory_deallocate( fsref ); string_deallocate( pathstripped ); if( status == 0 ) { pid_t pid = 0; GetProcessPID( &psn, &pid ); proc->pid = pid; //Always "detached" with LSOpenApplication, not a child process at all //Setup a kqueue to watch when process terminates so we can emulate a wait proc->kq = kqueue(); if( proc->kq < 0 ) { log_warnf( 0, WARNING_SYSTEM_CALL_FAIL, "Unable to create kqueue for process watch: %s (%d)", proc->kq, system_error_message( proc->kq ) ); proc->kq = 0; } else { struct kevent changes; EV_SET( &changes, (pid_t)pid, EVFILT_PROC, EV_ADD | EV_RECEIPT, NOTE_EXIT, 0, 0 ); int ret = kevent( proc->kq, &changes, 1, &changes, 1, 0 ); if( ret != 1 ) { log_warnf( 0, WARNING_SYSTEM_CALL_FAIL, "Unable to setup kqueue for process watch, failed to add event to kqueue (%d)", ret ); close( proc->kq ); proc->kq = 0; } } } goto exit; } #endif #if FOUNDATION_PLATFORM_POSIX //Insert executable arg at start and null ptr at end int argc = array_size( proc->args ) + 1; array_grow( proc->args, 2 ); for( int arg = argc - 1; arg > 0; --arg ) proc->args[arg] = proc->args[arg-1]; proc->args[0] = string_clone( proc->path ); proc->args[argc] = 0; if( proc->flags & PROCESS_STDSTREAMS ) { proc->pipeout = pipe_allocate(); proc->pipein = pipe_allocate(); } proc->pid = 0; pid_t pid = fork(); if( pid == 0 ) { //Child if( string_length( proc->wd ) ) { log_debugf( 0, "Spawned child process, setting working directory to %s", proc->wd ); environment_set_current_working_directory( proc->wd ); } log_debugf( 0, "Child process executing: %s", proc->path ); if( proc->flags & PROCESS_STDSTREAMS ) { pipe_close_read( proc->pipeout ); dup2( pipe_write_fd( proc->pipeout ), STDOUT_FILENO ); pipe_close_write( proc->pipein ); dup2( pipe_read_fd( proc->pipein ), STDIN_FILENO ); } int code = execv( proc->path, proc->args ); if( code < 0 ) //Will always be true since this point will never be reached if execve() is successful log_warnf( 0, WARNING_BAD_DATA, "Child process failed execve() : %s : %s", proc->path, system_error_message( errno ) ); //Error process_exit( -1 ); } if( pid > 0 ) { log_debugf( 0, "Child process forked, pid %d", pid ); proc->pid = pid; if( proc->pipeout ) pipe_close_write( proc->pipeout ); if( proc->pipein ) pipe_close_read( proc->pipein ); if( proc->flags & PROCESS_DETACHED ) { int cstatus = 0; pid_t err = waitpid( pid, &cstatus, WNOHANG ); if( err == 0 ) { //TODO: Ugly wait to make sure process spawned correctly thread_sleep( 500 ); err = waitpid( pid, &cstatus, WNOHANG ); } if( err > 0 ) { //Process exited, check code proc->code = (int)((char)WEXITSTATUS( cstatus )); log_debugf( 0, "Child process returned: %d", proc->code ); return proc->code; } } } else { //Error proc->code = errno; log_warnf( 0, WARNING_BAD_DATA, "Unable to spawn process: %s : %s", proc->path, system_error_message( proc->code ) ); if( proc->pipeout ) stream_deallocate( proc->pipeout ); if( proc->pipein ) stream_deallocate( proc->pipein ); proc->pipeout = 0; proc->pipein = 0; return proc->code; } #endif #if !FOUNDATION_PLATFORM_WINDOWS && !FOUNDATION_PLATFORM_POSIX FOUNDATION_ASSERT_FAIL( "Process spawning not supported on platform" ); #endif #if FOUNDATION_PLATFORM_MACOSX exit: #endif if( proc->flags & PROCESS_DETACHED ) return PROCESS_STILL_ACTIVE; return process_wait( proc ); }
bool CHttpDownloader::GetToFile(const char *url, const char *dest, unsigned timeOut, unsigned downloadSpeed) { if (!dest || dest[0] == 0) return false; int64 downloadTime = time_get(); unsigned chunkBytes = 0; NETSOCKET sock; NETADDR nadd, bindAddr; mem_zero(&nadd, sizeof(nadd)); mem_zero(&bindAddr, sizeof(bindAddr)); bindAddr.type = NETTYPE_IPV4; NETURL NetUrl = CreateUrl(url); if (net_host_lookup(NetUrl.m_aHost, &nadd, NETTYPE_IPV4) != 0) { dbg_msg("HttpDownloader", "Error can't found '%s'...", NetUrl.m_aHost); return false; } nadd.port = 80; sock = net_tcp_create(bindAddr); if (net_tcp_connect(sock, &nadd) != 0) { dbg_msg("HttpDownloader", "Error can't connect with '%s'...", NetUrl.m_aHost); net_tcp_close(sock); return false; } net_socket_rcv_timeout(sock, timeOut); char aBuff[512] = {0}; str_format(aBuff, sizeof(aBuff), "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", NetUrl.m_aSlug, NetUrl.m_aHost); net_tcp_send(sock, aBuff, str_length(aBuff)); std::string NetData; unsigned TotalRecv = 0; unsigned TotalBytes = 0; int CurrentRecv = 0; unsigned nlCount = 0; char aNetBuff[1024] = {0}; IOHANDLE dstFile = NULL; do { // Limit Speed if (downloadSpeed > 0) { int64 ctime = time_get(); if (ctime - downloadTime <= time_freq()) { if (chunkBytes >= downloadSpeed) { int tdff = (time_freq() - (ctime - downloadTime)) / 1000; thread_sleep(tdff); continue; } } else { chunkBytes = 0; downloadTime = time_get(); } } // CurrentRecv = net_tcp_recv(sock, aNetBuff, sizeof(aNetBuff)); chunkBytes += CurrentRecv; for (int i=0; i<CurrentRecv ; i++) { if (nlCount < 2) { if (aNetBuff[i] == '\r' || aNetBuff[i] == '\n') { ++nlCount; if (NetData.size() > 0) { std::transform(NetData.begin(), NetData.end(), NetData.begin(), ::tolower); if (NetData.find("404 not found") != std::string::npos) { dbg_msg("HttpDownloader", "ERROR 404: '%s' not found...", NetUrl.m_aFile); net_tcp_close(sock); return false; } else if (NetData.find("content-length:") != std::string::npos) { char aFileSize[64]; str_copy(aFileSize, NetData.substr(15).c_str(), sizeof(aFileSize)); str_trim(aFileSize); TotalBytes = atoi(aFileSize); } NetData.clear(); } if (aNetBuff[i] == '\r') ++i; continue; } nlCount = 0; NetData += aNetBuff[i]; } else { if (nlCount == 2) { if (TotalBytes <= 0) { dbg_msg("HttpDownloader", "Error downloading '%s'...", NetUrl.m_aFile); net_tcp_close(sock); return false; } dstFile = io_open(dest, IOFLAG_WRITE); if(!dstFile) { dbg_msg("HttpDownloader", "Error creating '%s'...", dest); net_tcp_close(sock); return false; } ++nlCount; } io_write(dstFile, &aNetBuff[i], 1); TotalRecv++; if (TotalRecv == TotalBytes) break; } } } while (CurrentRecv > 0); net_tcp_close(sock); if (TotalRecv > 0) { io_close(dstFile); return true; } return false; }