コード例 #1
0
void initialize_system ()
{
    
   FILE *fconfig;

  fconfig = fopen ("config.sys", "r");
  fscanf (fconfig, "%d\n", &Observe);
  fscanf (fconfig, "%d %d\n", &cpuQuantum, &idleQuantum);
  fscanf (fconfig, "%d %d %d %d\n", &pageSize, &memSize, &swapSize, &OSmemSize);
  fscanf (fconfig, "%d\n", &periodAgeScan);
  fscanf (fconfig, "%d\n", &spoolPsize);
  fclose (fconfig);
    
    OriginalPages= find_pages(memSize,pageSize);
    OriginalPages_swapspace = find_pages(swapSize,pageSize);

    rem_pages = OriginalPages;
    rem_pages_swapspace = OriginalPages_swapspace;

    #undef num_pages
    #define num_pages OriginalPages;
    
    OSpages= find_pages(OSmemSize,pageSize);
    
    printf("OS Size is %d , OS pages are %d\n", OSmemSize, OSpages);
    
    rem_pages= OriginalPages-OSpages;
    
    idlePages= find_pages(3, pageSize);

 /*printf("Idle Size is 256, Idle pages are %d, rem pages are %d \n", idlePages, rem_pages);
    
    rem_pages = rem_pages-idlePages;*/
    
    printf("remaining pages are %d\n", rem_pages);
    
    
     #undef num_pages
     #define num_pages rem_pages;
   
   printf("Number of frames in Main memory is %d remaininng pages are %d\n", OriginalPages, rem_pages);
   
    
  initialize_cpu ();
    printf("initialized CPU \n");
  initialize_swap_freelist(rem_pages_swapspace, OriginalPages_swapspace);
     printf("initialized Swap Space \n");
  initialize_freelist(rem_pages, OriginalPages);
    printf("initialized Main Memory \n");  
   initialize_timer ();
     printf("initialized timer \n");
   initialize_memory ();
      printf("initialized memory \n");
  initialize_process ();
      printf("initialized process \n");
     //   initialize_memory ();
   // printf("initialized memory \n");
  
}
コード例 #2
0
ファイル: bsp_init.c プロジェクト: RemiLatapy/INF3610_Lab2
int initialize_bsp() {
	disable_cache_for_section();
	initialize_irq_gen_0();
	initialize_irq_gen_1();
	initialize_timer();

	return XST_SUCCESS;
}
コード例 #3
0
int init_workqueue(void)
{
	//printk(KERN_INFO "workqueue init called\n");
	initialize_timer();//Initializing timer
	create_work_queue(); //calling workqueue
	//printk(KERN_INFO "workqueue init done\n");
	//queue_work( my_wq, &wk1->work );
	return 0;
}
コード例 #4
0
ファイル: test_uloop.c プロジェクト: jwhu1024/uloop
int main(int argc, char **argv)
{
	// uloop initialize
	uloop_init();

	// setTimeout
	struct uloop_timeout *timeout;
	initialize_timer(timeout, SET_TIMEOUT);
	
	// setInternal
	struct uloop_timeout *interval;
	initialize_timer(interval, SET_INTERVAL);
	
	// loop start
	uloop_run();
	uloop_done();

	return 0;
}
コード例 #5
0
int main (int argv, char** argc) 
{
	int tds = 1;
	int nn = ARRAY_SIZE;
	int w = 16;

	if (argv > 1) {
		tds = atoi(argc[1]);
	}
	if (argv > 2) {
		w = atoi(argc[2]);
	}

	int w2 = 2*w;

	if (ARRAY_SIZE%w2 != 0) {
		printf("Error: Array size: %d is not a multiple of 2*weight: %d!\n", ARRAY_SIZE, w2);
		exit(-1);
	}


	int i = 0;

	int *sum = (int *)malloc(tds*sizeof(int));
	
	initialize_timer();
	start_timer();

	#pragma omp parallel num_threads(tds)
	{
		int tid = 0;
#ifdef OMP
		tid = omp_get_thread_num();
#endif
		int rr = oneThread(tid, w);
		sum[tid] = rr;
	}
	
	stop_timer();
	double vector_time = elapsed_time();
	double gops = (double)((double)((double)((double)4*(double)4)*(double)REPS*((((double)ARRAY_SIZE)/(double)w2)-1.0f)*(double)tds)/vector_time)/((double)1e9);
	//double gops = (double)((double)((double)((double)2*(double)4)*(double)REPS*(double)VECTOR_ARRAY_SIZE*(double)ARRAY_SIZE)/vector_time)/((double)1e9);
	fprintf(stdout, "Threads: %d ArraySize: %d W: %d time: %.2f s GOPS: %.2f\n", tds, ARRAY_SIZE, w, vector_time, gops);
	
	int out = 0;
	for(i = 0; i < tds; i++){
		out += sum[i];
	}

	printf("sum: %d\n", out);

	return 0;
} 
コード例 #6
0
int main(int argc, char** argv)
{
    srand(time(NULL));

    initialize_state();

    initialize_timer();

    print_state(stdout, 1.0f);
    printf("Score: %d\n", game_state.score);

    char input;

    double dTime = 0;
    while (1)
    {
        dTime += get_elapsed_time();
        if (dTime > 1)
        {
            printf("Tick.\n");
            dTime -= 1;
        }
    }

    while (input = getchar())
    {
        switch (input)
        {
        case 'D':
            if (move_down()) return 0;
            break;
        case 'G':
            if (gravity_tick()) return 0;
            break;
        case 'L':
            move_left();
            break;
        case 'R':
            move_right();
            break;
        case 'U':
            rotate();
            break;
        }
        print_state(stdout, 1.0f);
        printf("Score: %d\n", game_state.score);
    }

    return 0;
}
コード例 #7
0
int main()
{
	DDRB = 0b00011100;
	DDRD = 0b01111100;

	sei();
	initialize_timer();
	serial_init(65);

	usi_i2c_slave_address = eeprom_read_byte((uint8_t*)1);
	if((usi_i2c_slave_address < 0x04) || (usi_i2c_slave_address > 0x77))
	{
		//If the stored address is out of range, default to 0x66.
		usi_i2c_slave_address = 0x66;
	}

	//USI_I2C_Init(usi_i2c_slave_address);

//master init
	DDR_USI  |= (1 << PORT_USI_SDA) | (1 << PORT_USI_SCL);
	PORT_USI |= (1 << PORT_USI_SCL);
	PORT_USI |= (1 << PORT_USI_SDA);
		USIDR = 0xFF;
		USICR = (0 << USISIE) | (0 << USIOIE) | (1 << USIWM1) | (0 << USIWM0) | (1 << USICS1) | (0 << USICS0) | (1 << USICLK) | (0 << USITC);
		USISR = (1 << USISIF) | (1 << USIOIF) | (1 << USIPF)  | (1 << USIDC)  | (0x00 << USICNT0);
	
	USI_Slave_register_buffer[0] = (unsigned char*)&step_compare;
	USI_Slave_register_buffer[1] = (unsigned char*)(&step_compare)+1;
	USI_Slave_register_buffer[2] = (unsigned char*)&step_count;
	USI_Slave_register_buffer[3] = (unsigned char*)(&step_count)+1;
	USI_Slave_register_buffer[4] = &step_dir;
	USI_Slave_register_buffer[5] = &step_mode;
	USI_Slave_register_buffer[6] = &step_enabled;
	USI_Slave_register_buffer[7] = &step_enabled;
	while(1)
	{
		if(step_compare != OCR1A)
		{
			OCR1A = step_compare;
		}
		process_serial_message();
	}
}
コード例 #8
0
ファイル: test.c プロジェクト: gwAdvNet2015/gw-kv-store
int main(){
        timer_util* tu = malloc(sizeof(timer_util));
        int i, j, k;
        initialize_timer(tu);
        struct histogram* hist = histogram_create(0, 20000, 10);
        for(i = 0; i < NUM_TIMER; i++){
                timer_set_mode(tu, i, 1);
        }
        for(i = 0; i < 100; i++){
                for(j = 0; j < NUM_TIMER; j++){
                        timer_start(tu, j);
                        for(k = 0; k < 1000000; k++){}
                        timer_end_hist(tu, j, hist);
                        printf("Timer #%d min: %"PRIu64"\n", j, timer_min(tu, j));
                        printf("Timer #%d max: %"PRIu64"\n", j, timer_max(tu, j));
                        printf("Timer #%d avg: %"PRIu64"\n\n", j, timer_avg(tu, j));
                }
        }
        histogram_print(hist);
        return 0;
}
コード例 #9
0
ファイル: c_entry.cpp プロジェクト: pavelruban-org/arm
extern "C" void __initialize_hardware()
{
	// Avoid peripheal libs additional init code.
	#define RCC_APB2Periph_SPIz_Enabled
	#define RCC_APB2Periph_SPIy_Enabled
	#define RCC_APB2Periph_ETH_Enabled
	#define RCC_APB2Periph_RC522_Enabled
	#define RCC_APB2Periph_RC522_2_Enabled

	/* Enable GPIOC clock */
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

	/* Configure PC.4 as Output push-pull */
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	/* Configure PC.4 as Output push-pull */
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	// initialize peripheal hardware pins.
	rc522_set_pins();
	rc522_2_set_pins();
	enc28j60_set_pins();

	// Initilize SPIz hardware settings (pins and spi registers).
	set_spi_registers();
	set_spi2_registers();

	interrupt_initialize();
	initialize_timer();
	initialize_systick();
}
	void task_loop(void *p) {
		initialize_timer();
		adc->enable_channel(ADC_CH0);
		mux->enable();
		AdcEvent current_event;
		for(;;) {
			xQueueReceive(event_queue, &current_event, portMAX_DELAY);
			switch (current_event) {
			case AdcEvent::ADC_SCAN:
			{
				AnalogSensorMessage msg_to_send;
				for (int i = 0; i < 16; ++i) {
					uint16_t adc_data;
					mux->select_channel(i);
					adc->read_value(ADC_CH0, &adc_data);
					AdcSensorValue val = MUX_INPUT_POLYNOMIAL_A_VALUES[i] * adc_data + MUX_INPUT_POLYNOMIAL_B_VALUES[i];
					msg_to_send.adc_values[i] = val;
				}
				nav_computer_task::add_message_to_outgoing_frame(msg_to_send);
				break;
			}
			}
		}
	}
コード例 #11
0
ファイル: driver.c プロジェクト: AmirAbrams/haiku
status_t
init_driver(void)
{
	struct pci_info *item;
	int index;
	int cards;

#ifdef DEBUG	
	set_dprintf_enabled(true);
	load_driver_symbols("ipro1000");
#endif
	
	dprintf("ipro1000: " INFO "\n");
	
	item = (pci_info *)malloc(sizeof(pci_info));
	if (!item)
		return B_NO_MEMORY;
	
	if (get_module(B_PCI_MODULE_NAME, (module_info **)&gPci) < B_OK) {
		free(item);
		return B_ERROR;
	}
	
	for (cards = 0, index = 0; gPci->get_nth_pci_info(index++, item) == B_OK; ) {
		const char *info = identify_device(item);
		if (info) {
			char name[64];
			sprintf(name, "net/ipro1000/%d", cards);
			dprintf("ipro1000: /dev/%s is a %s\n", name, info);
			gDevList[cards] = item;
			gDevNameList[cards] = strdup(name);
			gDevNameList[cards + 1] = NULL;
			cards++;
			item = (pci_info *)malloc(sizeof(pci_info));
			if (!item)
				goto err_outofmem;
			if (cards == MAX_CARDS)
				break;
		}
	}

	free(item);

	if (!cards)
		goto err_cards;
		
	if (initialize_timer() != B_OK) {
		ERROROUT("timer init failed");
		goto err_timer;
	}

	if (mempool_init(cards * 768) != B_OK) {
		ERROROUT("mempool init failed");
		goto err_mempool;
	}
	
	return B_OK;

err_mempool:
	terminate_timer();
err_timer:
err_cards:
err_outofmem:
	for (index = 0; index < cards; index++) {
		free(gDevList[index]);
		free(gDevNameList[index]);
	}
	put_module(B_PCI_MODULE_NAME);
	return B_ERROR;
}
コード例 #12
0
int main(int argc, char **argv) {

   int     N;
   int     t;
   int     MAX_ITERATION = 2000;
   double  *prev, *cur;
   double  error = INIT_VALUE;

   // Timer
   double  time;

   // temporary variables
   int     i,j;
   double  *temp;

   // Check commandline args.
   if ( argc > 1 ) {
      N = atoi(argv[1]);
   } else {
      printf("Usage : %s [N]\n", argv[0]);
      exit(1);
   }
   if ( argc > 2 ) {
      MAX_ITERATION = atoi(argv[2]);
   }

   // Memory allocation for data array.
   prev  = (double *) malloc( sizeof(double) * N * N );
   cur   = (double *) malloc( sizeof(double) * N * N );
   if ( prev == NULL || cur == NULL ) {
      printf("[ERROR] : Fail to allocate memory.\n");
      exit(1);
   }

   // Initialization
   for ( i=1 ; i < N-1 ; i++ ) {
      for ( j=1 ; j < N-1 ; j++ ) {
         prev(i,j) = 0.0;
      }
   }
   for ( i=0 ; i < N ; i++ ) {
      prev(i  , 0  )  = INIT_VALUE;
      prev(i  , N-1)  = INIT_VALUE;
      prev(0  , i  )  = INIT_VALUE;
      prev(N-1, i  )  = INIT_VALUE;
      cur( i  , 0  )  = INIT_VALUE;
      cur( i  , N-1)  = INIT_VALUE;
      cur( 0  , i  )  = INIT_VALUE;
      cur( N-1, i  )  = INIT_VALUE;
   }

   initialize_timer();
   start_timer();

   // Computation
   t = 0;

   while ( t < MAX_ITERATION) {

      // Computation
      #pragma omp parallel for schedule(runtime)
      for ( i=1 ; i < N-1 ; i++ ) 
      {
	for ( j=1 ; j < N-1 ; j++ )
        {
	   cur(i,j) = ((prev(i-1,j-1)+prev(i-1,j)+prev(i-1,j+1)+prev(i,j-1)+prev(i,j)+prev(i,j+1)+prev(i+1,j-1)+prev(i+1,j)+prev(i+1,j+1)))/9;
        }
      }

      temp = prev;
      prev = cur;
      cur  = temp;
      t++;

   }

   stop_timer();
   time = elapsed_time();

   printf("Data : %d by %d , Iterations : %d , Time : %lf sec\n", N, N, t, time);
   printf("Final data\n");
   printMatrix(prev, N);



}
コード例 #13
0
ファイル: client-simple.cpp プロジェクト: Albinpa/MPCSN
//--    main()              ///{{{1///////////////////////////////////////////
int main( int argc, char* argv[] )
{
	const char* serverPort = 0;
	const char* serverAddress = 0;

	// get program arguments (server address and port)
	if( argc != 3 )
	{
		fprintf( stderr, "Error %s arguments\n", 
			argc < 3 ? "insufficient":"too many" 
		);
		fprintf( stderr, "  usage: %s <server> <port>\n", argv[0] );
		return 1;
	}

	serverPort = argv[2];
	serverAddress = argv[1];

	// initialize timer(s)
#	if MEASURE_ROUND_TRIP_TIME
	initialize_timer();
#	endif

	// establish connection to server
	int connfd = connect_to_server( serverAddress, serverPort );

	if( -1 == connfd )
		return 1;

	// main loop: read user input, send to server and receive server reply
	while( 1 )
	{
		char inputBuffer[kInputBufferSize];

		// get input from user
		printf( "Input> " );
		if( !fgets( inputBuffer, kInputBufferSize, stdin ) )
			break; // typically EOF, possibly error - either way: exit!

		// strip trailing '\n'
		size_t inputLength = strlen(inputBuffer);
		if( inputBuffer[inputLength-1] == '\n' )
			inputBuffer[--inputLength] = '\0';

		// print status
#		if VERBOSE
		printf( "Sending string `%s' (%zu bytes)\n", inputBuffer, inputLength );
#		endif

		// timing - query start time
#		if MEASURE_ROUND_TRIP_TIME
		double startTime = get_time_stamp();
#		endif

		// send input to server
		ssize_t remaining = inputLength;
		while( remaining > 0 )
		{
			ssize_t offset = inputLength - remaining;
			ssize_t ret = send( connfd, 
				inputBuffer+offset, 
				remaining,
				MSG_NOSIGNAL
			);

			if( -1 == ret )
			{
				perror( "send() failed" );
				return 1;
			}

			remaining -= ret;
		}

		// get response from server
		char recvBuffer[kReceiveBufferSize+1];

		size_t received = 0;
		size_t expected = std::min( kReceiveBufferSize, inputLength );

		while( received < expected )
		{
			ssize_t ret = recv( connfd,
				recvBuffer + received,
				expected-received,
				0
			);

			if( 0 == ret )
			{
				fprintf( stderr, "Error - connection closed unexpectedly!\n" );
				return 1;
			}
			if( -1 == ret )
			{
				perror( "recv() failed" );
				return 1;
			}

			received += ret;
		}

		// timing - query end time
#		if MEASURE_ROUND_TRIP_TIME
		double endTime = get_time_stamp();
#		endif

		// ensure that the received string is zero-terminated
		recvBuffer[received] = '\0';

		// print output to screen
		printf( "Response = `%s'\n", recvBuffer );
#		if VERIFY_MESSAGE
		bool match = 0 == strncmp( inputBuffer, recvBuffer, 
			std::min( kInputBufferSize, kReceiveBufferSize )
		);

		printf( "  - response does %smatch original query\n",
			match ? "" : "NOT "
		);
#		endif
#		if MEASURE_ROUND_TRIP_TIME
		printf( "  - round trip time is %f ms\n", (endTime-startTime)*1e3 );
#		endif
	}

	// clean up
	close( connfd );

	return 0;
}
コード例 #14
0
int main (int argv, char** argc) 
{
	tds = 1;
//	reps = REPS;
	
	if (argv > 1) {
		tds = atoi(argc[1]);
	}
/*	if (argv > 2) {
		reps = atoi(argc[2]);
	}
*/

	int i = 0;

	sum = (int *)malloc(tds*sizeof(int));
	
	initialize_timer();
	start_timer();

	mykernel(NULL);

	stop_timer();
	double vector_time = elapsed_time();

	reset_timer();
	start_timer();

	mykernel(NULL);

	stop_timer();
	double vector_time_01 = elapsed_time();

	double gops = (double)((double)ARRAY_SIZE*(double)REPS*(double)tds*(double)2)/vector_time/((double)1e9);
	double bw = (double)((double)ARRAY_SIZE*(double)REPS)*(double)2*(double)4*(double)tds/vector_time/((double)1e9);
	double gops01 = (double)((double)ARRAY_SIZE*(double)REPS*(double)tds*(double)2)/vector_time_01/((double)1e9);
	double bw1 = (double)((double)ARRAY_SIZE*(double)REPS)*(double)2*(double)4*(double)tds/vector_time_01/((double)1e9);
	fprintf(stdout, "Threads: %d ArraySize: %d time: %.2f s GOPS: %.2f time01: %.2f s GOPS01: %.2f REPS: %d BW: %.2f BW1: %.2f\n", tds, ARRAY_SIZE, vector_time, gops, vector_time_01, gops01, REPS, bw, bw1);

	my_papi_profile(mykernel);

/*#pragma omp parallel num_threads(tds)
	{
		int tid = 0;
#ifdef OMP
		tid = omp_get_thread_num();
#endif
		int rr = oneThread(tid);
		sum[tid] = rr;
	}
*/
	
	int out = 0;
	for(i = 0; i < tds; i++){
		out += sum[i];
	}

	printf("sum: %d\n", out);

	return 0;
} 
コード例 #15
0
int main()
{
    int i;
    int btns_check, sws_check;
    int ld9_toggle;

    int uiofd0;  // AXI timer
    int uiofd1;  // btns_8bits
    int uiofd2;  // leds_8bits
    int uiofd3;  // sws_8bits
    const char *uiod0 = "/dev/uio0";
    const char *uiod1 = "/dev/uio1";
    const char *uiod2 = "/dev/uio2";
    const char *uiod3 = "/dev/uio3";
    void *uioptr0;
    void *uioptr1;
    void *uioptr2;
    void *uioptr3;


	printf("-- Example program --\n");

	// Open the UIO devices

	uiofd0 = open(uiod0, O_RDWR);
	if (uiofd0 < 1) {
		printf("Invalid UIO device file:%s.\n", uiod0);
		exit(-1);
	}

	uiofd1 = open(uiod1, O_RDWR);
	if (uiofd1 < 1) {
		printf("Invalid UIO device file:%s.\n", uiod1);
		exit(-1);
	}

	uiofd2 = open(uiod2, O_RDWR);
	if (uiofd2 < 1) {
		printf("Invalid UIO device file:%s.\n", uiod2);
		exit(-1);
	}

	uiofd3 = open(uiod3, O_RDWR);
	if (uiofd3 < 1) {
		printf("Invalid UIO device file:%s.\n", uiod3);
		exit(-1);
	}

	// mmap() the UIO devices
	uioptr0 = mmap(NULL, UIO_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, uiofd0, 0);
	if (uioptr0 == MAP_FAILED) {
		printf("mmap call failure.\n");
		exit(-1);
	}

	uioptr1 = mmap(NULL, UIO_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, uiofd1, 0);
	if (uioptr1 == MAP_FAILED) {
		printf("mmap call failure.\n");
		exit(-1);
	}

	uioptr2 = mmap(NULL, UIO_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, uiofd2, 0);
	if (uioptr2 == MAP_FAILED) {
		printf("mmap call failure.\n");
		exit(-1);
	}

	uioptr3 = mmap(NULL, UIO_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, uiofd3, 0);
	if (uioptr3 == MAP_FAILED) {
		printf("mmap call failure.\n");
		exit(-1);
	}

	// Initialize timer
	timer_baseaddr = uioptr0;
	timer_baseaddr_u32 = (unsigned int *) uioptr0;
	timer_fd = uiofd0;
	initialize_timer();

	//printf("TCSR0=0x%08X TLR0=0x%08X TCR0=0x%08X\n", read32(timer_baseaddr, 0x0), read32(timer_baseaddr, 0x4), read32(timer_baseaddr, 0x8));


    printf("-- Press BTNR push button to change the LD9 toggle --\n");
    printf("-- Press BTND push button to start the Timer interrupt --\n");
    printf("-- Press BTNL push button to exit --\n");
    printf("-- Change slide switches to see corresponding output on LEDs --\n");

    ld9_toggle = 0;
    //InterruptFlag = 0;

    while(1)
    {
    	btns_check = *((volatile unsigned *) uioptr1);
    	//printf("Buttons Status %x\n", btns_check);
    	sws_check = *((volatile unsigned *) uioptr3);
    	//printf("Switches Status %x\n", sws_check);

    	*((volatile unsigned *) uioptr2) = sws_check;

    	if ((btns_check & 0x08) == 0x08) {
            printf("BTNR is pressed\n");
            printf("Changing the LD9 toggle\n");
            ld9_toggle = !ld9_toggle;  // FIXME
    	}

    	if ((btns_check & 0x02) == 0x02) {
            printf("BTND is pressed\n");
            printf("Starting the Timer\n");
            // Start Timer
            start_timer();
            // Wait for interrupt
            wait_for_interrupt();
    	}

    	if ((btns_check & 0x04) == 0x04) {
            printf("BTNL is pressed\n");
            printf("Exiting\n");
            break;
    	}

    	for (i=0; i<999999999; i++); // delay loop
    }  // end while loop

	printf("-- Exiting main() --\n");

	// Unmap the UIO devices

	munmap(uioptr0, UIO_SIZE);
	munmap(uioptr1, UIO_SIZE);
	munmap(uioptr2, UIO_SIZE);
	munmap(uioptr3, UIO_SIZE);

    return 0;
}
コード例 #16
0
ファイル: client-multi.cpp プロジェクト: guitarfriiik/EDA387
//--    main()              ///{{{1///////////////////////////////////////////
int main( int argc, char* argv[] )
{
	size_t numClients = 1;
	size_t numRepeats = 1;

	const char* serverPort = 0;
	const char* serverAddress = 0;

	// get program arguments (server address and port)
	if( argc < 4 || argc > 6 )
	{
		fprintf( stderr, "Error %s arguments\n", 
			argc < 4 ? "insufficient":"too many" 
		);
		fprintf( stderr, "  synopsis: %s <server> <port> <#num> [<#rep>] [<msg>]\n", 
			argv[0] 
		);
		fprintf( stderr, "    - <#num> -- number of clients to be emulated\n" );
		fprintf( stderr, "    - <#rep> -- number of times message is sent\n" );
		fprintf( stderr, "    - <msg> -- message sent by clients (see below)\n" );
		fprintf( stderr, "\n" );
		fprintf( stderr, "If the client message includes a `%%d' place holder, it\n" );
		fprintf( stderr, "is replaced by an unique client id (0 < cid < #clients)\n" );
		fprintf( stderr, "before the message is sent to the server.\n" );
		fprintf( stderr, "The default message is `%s'\n", g_clientMessage );
		return 1;
	}

	serverPort = argv[2];
	serverAddress = argv[1];

	numClients = atol(argv[3]);

	if( argc >= 5 ) numRepeats = atol(argv[4]);
	if( argc >= 6 ) g_clientMessage = argv[5];

	// print short status
	printf( "Simulating %zu clients.\n", numClients );

	// initialize timer(s)
#	if MEASURE_ROUND_TRIP_TIME
	initialize_timer();
#	endif

	// resolve address of server once
	sockaddr_in servAddr;
	if( !resolve_address( servAddr, serverAddress, serverPort ) )
		return 1;

	// establish N connections (async)
	printf( "Establishing %zu connections... \n", numClients );

	size_t connErrors = 0;
	ConnectionData* connections = new ConnectionData[numClients];

	for( size_t i = 0; i < numClients; ++i )
	{
#		if MEASURE_CONNECT_TIME
		connections[i].connectEnd = connections[i].connectStart = -1.0;
		connections[i].connectStart = get_time_stamp();
#		endif

		connections[i].sock = connect_to_server_nonblock( servAddr );
		connections[i].state = eConnStateConnecting;

		// initialize client aux. data
		connections[i].repeatsLeft = numRepeats-1;
	
#		if MEASURE_ROUND_TRIP_TIME
		connections[i].roundTripEnd = connections[i].roundTripStart = -1.0;
#		endif

		// on error: mark client as dead
		if( -1 == connections[i].sock )
		{
			connections[i].state = eConnStateDead;
			++connErrors;
		}
	}

	if( connErrors > 0 )
	{
		printf( "  %zu errors while establishing connections\n", connErrors );

		if( connErrors == numClients )
		{
			printf( "All clients errored. Bye\n" );
			return 1;
		}
	}

	printf( "  successfully initiated %zu connection attempts!\n", 
		numClients-connErrors );

	// event handling loop
	size_t clientsAlive = numClients - connErrors;

	while( clientsAlive > 0 )
	{
		int maxfd = 0;
		fd_set rset, wset;

		FD_ZERO( &rset ); 
		FD_ZERO( &wset );

		// put active clients into their respective sets
		for( size_t i = 0; i < numClients; ++i )
		{
			switch( connections[i].state )
			{
				case eConnStateSending:
				case eConnStateConnecting:
					FD_SET( connections[i].sock, &wset );
					break;

				case eConnStateReceiving:
					FD_SET( connections[i].sock, &rset );
					break;

				case eConnStateDead: break;
			}

			maxfd = std::max( connections[i].sock, maxfd );
		}

		// wait for any event
		int ret = select( maxfd+1, &rset, &wset, 0, 0 );

		if( 0 == ret )
		{
			continue;
		}

		if( -1 == ret )
		{
			perror( "select()" );
			return 1;
		}

		// handle events
		size_t finishedClients = 0;

		for( size_t i = 0; i < numClients; ++i )
		{
			if( connections[i].state == eConnStateDead ) continue;

			bool keep = true;
			if( FD_ISSET( connections[i].sock, &wset ) )
			{
				keep = client_process_send( i, connections[i] );
			}
			else if( FD_ISSET( connections[i].sock, &rset ) )
			{
				keep = client_process_recv( i, connections[i] );
			}

			if( !keep )
			{
				close( connections[i].sock );

				connections[i].sock = -1;
				connections[i].state = eConnStateDead;

				++finishedClients;
			}
		}

		clientsAlive -= finishedClients;
	}

	// gather and display some statistics
#	if MEASURE_CONNECT_TIME
	{
		double avgTime = 0.0;
		double maxTime = 0.0;
		double minTime = std::numeric_limits<double>::infinity();
		size_t timedItems = 0, erroredItems = 0;

		for( size_t i = 0; i < numClients; ++i )
		{
			if( connections[i].connectEnd < 0.0 )
			{
				++erroredItems;
				continue;
			}
			
			double delta = connections[i].connectEnd - connections[i].connectStart;

			minTime = std::min( delta, minTime );
			maxTime = std::max( delta, maxTime );
			avgTime += delta;
			++timedItems;

#		if VERBOSE
			printf( "  - conn %zu : connect time = %f ms\n", 
				i, delta*1e3 );
#		endif
		}

		avgTime /= timedItems;

		printf( "Connect timing results for %zu successful connections\n",
			timedItems );
		printf( "  - min time: %f ms\n", minTime*1e3 );
		printf( "  - max time: %f ms\n", maxTime*1e3 );
		printf( "  - average time: %f ms\n", avgTime*1e3 );
		printf( " (%zu connections failed!)\n", erroredItems );
	}
#	endif
#	if MEASURE_ROUND_TRIP_TIME
	{
		double avgTime = 0.0;
		double maxTime = 0.0;
		double minTime = std::numeric_limits<double>::infinity();
		size_t timedItems = 0;

		for( size_t i = 0; i < numClients; ++i )
		{
			if( connections[i].roundTripEnd < 0.0 ) continue;
			
			double delta = connections[i].roundTripEnd - connections[i].roundTripStart;

			minTime = std::min( delta, minTime );
			maxTime = std::max( delta, maxTime );
			avgTime += delta;
			++timedItems;

#		if VERBOSE
			printf( "  - conn %zu : round trip time = %f ms for %zu round trips\n", 
				i, delta*1e3, numRepeats );
#		endif
		}

		avgTime /= timedItems;

		printf( "Roundtrip timing results for %zu connections for %zu round trips\n",
			timedItems, numRepeats );
		printf( "  - min time: %f ms\n", minTime*1e3 );
		printf( "  - max time: %f ms\n", maxTime*1e3 );
		printf( "  - average time: %f ms\n", avgTime*1e3 );
	}
#	endif
	
	// clean up
	for( size_t i = 0; i < numClients; ++i )
		close( connections[i].sock );

	delete [] connections;
	
	return 0;
}
コード例 #17
0
ファイル: helper-main.c プロジェクト: cmjonze/mDNSResponder
int main(int ac, char *av[])
{
    char *p = NULL;
    kern_return_t kr = KERN_FAILURE;
    long n;
    int ch;
    mach_msg_header_t hdr;

    while ((ch = getopt(ac, av, "dt:")) != -1)
        switch (ch)
        {
        case 'd': opt_debug = 1; break;
        case 't':
            n = strtol(optarg, &p, 0);
            if ('\0' == optarg[0] || '\0' != *p || n > LONG_MAX || n < 0)
            { fprintf(stderr, "Invalid idle timeout: %s\n", optarg); exit(EXIT_FAILURE); }
            maxidle = n;
            break;
        case '?':
        default:
            fprintf(stderr, "Usage: mDNSResponderHelper [-d] [-t maxidle]\n");
            exit(EXIT_FAILURE);
        }
    ac -= optind;
    av += optind;
    (void)ac; // Unused
    (void)av; // Unused

    initialize_logging();
    helplog(ASL_LEVEL_INFO, "Starting");
    initialize_id();

#ifndef NO_SECURITYFRAMEWORK
    // We should normally be running as a system daemon.  However, that might not be the case in some scenarios (e.g. debugging).
    // Explicitly ensure that our Keychain operations utilize the system domain.
    if (opt_debug) SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
#endif
    gPort = register_service(kmDNSHelperServiceName);
    if (!gPort)
        exit(EXIT_FAILURE);

    if (maxidle) actualidle = maxidle;

    signal(SIGTERM, handle_sigterm);

    if (initialize_timer()) exit(EXIT_FAILURE);
    for (n=0; n<100000; n++) if (!gRunLoop) usleep(100);
    if (!gRunLoop)
    {
        helplog(ASL_LEVEL_ERR, "gRunLoop not set after waiting");
        exit(EXIT_FAILURE);
    }

    for(;;)
    {
        hdr.msgh_bits = 0;
        hdr.msgh_local_port = gPort;
        hdr.msgh_remote_port = MACH_PORT_NULL;
        hdr.msgh_size = sizeof(hdr);
        hdr.msgh_id = 0;
        kr = mach_msg(&hdr, MACH_RCV_LARGE | MACH_RCV_MSG, 0, hdr.msgh_size, gPort, 0, 0);
        if (MACH_RCV_TOO_LARGE != kr)
            helplog(ASL_LEVEL_ERR, "main MACH_RCV_MSG error: %d %X %s", kr, kr, mach_error_string(kr));

        kr = mach_msg_server_once(helper_server, MAX_MSG_SIZE, gPort,
                                  MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT) | MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0));
        if (KERN_SUCCESS != kr)
        { helplog(ASL_LEVEL_ERR, "mach_msg_server: %d %X %s", kr, kr, mach_error_string(kr)); exit(EXIT_FAILURE); }

    }
    exit(EXIT_SUCCESS);
}