Пример #1
0
int
main (int argc, char **argv)
{
	int i;
	double now;

	feenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);

	init_sdl_gl_flags (WIDTH, HEIGHT, 0);

	srandom (time (NULL));

	init_gl (&argc, argv);

	glEnable (GL_LIGHTING);
	glEnable (GL_DEPTH_TEST);
	glEnable (GL_AUTO_NORMAL);
	glEnable (GL_NORMALIZE);

	glClearDepth (1);
	
	glViewport (0, 0, WIDTH, HEIGHT);
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	gluPerspective (60, (GLfloat) WIDTH/(GLfloat) HEIGHT, .1, 1000);
	glClearColor (0, 0, 0, 0);
	glMatrixMode (GL_MODELVIEW);

	SDL_ShowCursor (1);

	makeImages ();

	glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
	glGenTextures (1, texName);
	
	makeTexture (texName[0], groundtexture.texturesize,
		     (GLubyte ***) groundtexture.tex);

	glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
	glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);

	glBlendFunc (GL_SRC_ALPHA, GL_ONE);

	gndcounter = 1;
	read_terrain ();

	player.p.x = 0;
	player.p.y = 0;
	player.p.z = ground_height (&player.p);

	player.loc = detect_plane (&player.p);

	player.movtype = GROUNDED;

	player.speed = 100;
	player.mass = 1;

	vset (&player.vel, 0, 0, 0);

	player.turnspeed = DTOR (180);
	player.theta = DTOR (0);
	player.camdist = 15;

	player.lasttime = get_secs ();
	player.moving = NO;

	playercamera.phi = DTOR (0);
	playercamera.theta_difference = 0;
	
	while (1) {
		process_input ();
		
		if (mousebutton[1] == 0
		    && mousebutton[2] == 0
		    && mousebutton[3] == 0) {
			SDL_ShowCursor (1);
		} else {
			SDL_ShowCursor (0);
		}

		movement ();
		if (paused == NO) {
			for (i = 0; i < 1; i++) {
				moving ();
				now = get_secs ();
				player.lasttime = now;
			}
		}

		process_mouse ();

		draw ();
		
		now = get_secs ();
		
		player.lasttime = now;

		SDL_Delay (10);
	}

	return (0);
}
Пример #2
0
int sqlite_main(int argc, char **argv){
	char *zErrMsg=0;
	struct callback_data data;
	char *zFirstCmd=0;
	int i;
	extern int sqliteOsFileExists(const char*);

	Argv0=argv[0];
	main_init(&data);

	// Make sure we have a valid signal handler early, before anything else is done.
	signal(SIGINT, interrupt_handler);

	// Do an initial pass through the command-line argument to locate
	// the name of the database file, the name of the initialization file,
	// and the first command to execute.
	for(i=1; i<argc-1; i++){
		if( argv[i][0]!='-' ) break;
		if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
			i++;
		}else if( strcmp(argv[i],"-key")==0 ){
			i++;
			data.zKey=sqlite_mprintf("%s",argv[i]);
		}
	}
	if( i<argc ){
		data.zDbFilename=argv[i++];
	}else{
		data.zDbFilename=":memory:";
	}
	if( i<argc ){
		zFirstCmd=argv[i++];
	}
	data.out=stdout;

	// Go ahead and open the database file if it already exists.  If the
	// file does not exist, delay opening it.  This prevents empty database
	// files from being created if a user mistypes the database name argument
	// to the sqlite command-line tool.

	if(sqliteOsFileExists(data.zDbFilename) ){
		open_db(&data);
	}

	// Process the initialization file if there is one.  If no -init option
	// is given on the command line, look for a file named ~/.sqliterc and
	// try to process it.
	process_sqliterc(&data);

	// Make a second pass through the command-line argument and set
	// options.  This second pass is delayed until after the initialization
	// file is processed so that the command-line arguments will override
	// settings in the initialization file.

	for(i=1; i<argc && argv[i][0]=='-'; i++){
		char *z=argv[i];
		if( strcmp(z,"-init")==0 || strcmp(z,"-key")==0 ){
			i++;
		}else if( strcmp(z,"-html")==0 ){
			data.mode=MODE_Html;
		}else if( strcmp(z,"-list")==0 ){
			data.mode=MODE_List;
		}else if( strcmp(z,"-line")==0 ){
			data.mode=MODE_Line;
		}else if( strcmp(z,"-column")==0 ){
			data.mode=MODE_Column;
		}else if( strcmp(z,"-separator")==0 ){
			i++;
			sprintf(data.separator,"%.*s",(int)sizeof(data.separator)-1,argv[i]);
		}else if( strcmp(z,"-nullvalue")==0 ){
			i++;
			sprintf(data.nullvalue,"%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
		}else if( strcmp(z,"-header")==0 ){
			data.showHeader=1;
		}else if( strcmp(z,"-noheader")==0 ){
			data.showHeader=0;
		}else if( strcmp(z,"-echo")==0 ){
			data.echoOn=1;
		}else if( strcmp(z,"-version")==0 ){
			printf("%s\n", sqlite_version);
			return 1;
		}else if( strcmp(z,"-help")==0 ){
			usage(1);
		}else{
			fprintf(stderr,"%s: unknown option: %s\n", Argv0, z);
			fprintf(stderr,"Use -help for a list of options.\n");
			return 1;
		}
	}

	if( zFirstCmd ){
		// Run just the command that follows the database name
		if( zFirstCmd[0]=='.' ){
			do_meta_command(zFirstCmd, &data);
			exit(0);
		}else{
			int rc;
			open_db(&data);
			rc=sqlite_exec(data.db, zFirstCmd, callback, &data, &zErrMsg);
			if( rc!=0 && zErrMsg!=0 ){
				fprintf(stderr,"SQL error: %s\n", zErrMsg);
				exit(1);
			}
		}
	}else{
		// Run commands received from standard input
		if( isatty(fileno(stdout)) && isatty(fileno(stdin)) ){
			char *zHistory=xmalloc(20);
			printf(
				"Mybox SQLite version %s\n"
				"Enter \".help\" for instructions\n",
				sqlite_version
			);
			sprintf(zHistory,"%s","/.sqlite_history");
			if( zHistory ) read_history(zHistory);
			process_input(&data, 0);
			if( zHistory ){
				stifle_history(100);
				write_history(zHistory);
			}
		}else{
			process_input(&data, stdin);
		}
	}
	set_table_name(&data, 0);
	if( db ) sqlite_close(db);
	return 0;
}
Пример #3
0
void
server_loop2(Authctxt *authctxt)
{
	fd_set *readset = NULL, *writeset = NULL;
	int rekeying = 0, max_fd;
	u_int nalloc = 0;
	u_int64_t rekey_timeout_ms = 0;

	debug("Entering interactive session for SSH2.");

	mysignal(SIGCHLD, sigchld_handler);
	child_terminated = 0;
	connection_in = packet_get_connection_in();
	connection_out = packet_get_connection_out();

	if (!use_privsep) {
		signal(SIGTERM, sigterm_handler);
		signal(SIGINT, sigterm_handler);
		signal(SIGQUIT, sigterm_handler);
	}

	notify_setup();

	max_fd = MAX(connection_in, connection_out);
	max_fd = MAX(max_fd, notify_pipe[0]);

	server_init_dispatch();

	for (;;) {
		process_buffered_input_packets();

		rekeying = (active_state->kex != NULL && !active_state->kex->done);

		if (!rekeying && packet_not_very_much_data_to_write())
			channel_output_poll();
		if (options.rekey_interval > 0 && compat20 && !rekeying)
			rekey_timeout_ms = packet_get_rekey_timeout() * 1000;
		else
			rekey_timeout_ms = 0;

		wait_until_can_do_something(&readset, &writeset, &max_fd,
		    &nalloc, rekey_timeout_ms);

		if (received_sigterm) {
			logit("Exiting on signal %d", (int)received_sigterm);
			/* Clean up sessions, utmp, etc. */
			cleanup_exit(255);
		}

		collect_children();
		if (!rekeying) {
			channel_after_select(readset, writeset);
			if (packet_need_rekeying()) {
				debug("need rekeying");
				active_state->kex->done = 0;
				kex_send_kexinit(active_state);
			}
		}
		process_input(readset);
		if (connection_closed)
			break;
		process_output(writeset);
	}
	collect_children();

	free(readset);
	free(writeset);

	/* free all channels, no more reads and writes */
	channel_free_all();

	/* free remaining sessions, e.g. remove wtmp entries */
	session_destroy_all(NULL);
}
Пример #4
0
NET_CODE esp8266_module::wifi_esp8266_init_net(CSocket * sock)
{
	NET_CODE res;
	CSTRING cmd;
	wifi_AP_t AP;
	uint32_t sig = 0;
	bool found;

	res = wifi_send_cmd("+CIFSR", 50);

	for(int i =0; i < 5; i++)
	{
		found = false;
		cmd_state |= WIFI_CMD_STATE_ROW_STOP;
		res = wifi_send_cmd("+CWLAP", 15);
		cmd_state &= ~WIFI_CMD_STATE_ROW_STOP;

		do
		{
			if(sig)
			{
				process_input(sig, "+CWLAP");
				res = cmd_state;
			}

			if (res >= WIFI_CMD_STATE_OK)
				break;

			if(res & WIFI_CMD_STATE_RETURNED)
			{
				cmd_state = res & ~WIFI_CMD_STATE_RETURNED;
				if(!found)
				{
					res = wifi_on_get_AP(this, sock, &AP);
					if(res == RES_OK)
						found = true;
				}
				row_start = 0;
				row_end = 0;
			}

			sig = tsk_resume_wait_signal(rcv_hnd.signal);
		} while(sig);

		if(cmd_state & WIFI_CMD_STATE_OK)
		{
			if(!found)
				res = NET_ERR_WIFI_NET_NAME;
			else
				res = NET_OK;
			break;
		}
	}
	if (res != NET_OK)
		return wifi_error(res);

	// If the wifi is already connected to a network different than the one
	// requested - return NET_IDLE - unavailable
	if (NET_OK == wifi_get_network_name(cmd))
	{
		if (0 != strcmp(cmd.c_str(), AP.name.c_str()))
		{
			return NET_IDLE;
		}
	}

	cmd.format("+CWJAP=\"%s\",\"%s\"", AP.name.c_str(), AP.pass.c_str());
	for(int i=0; i < 3; i++)
	{
		res = wifi_send_cmd(cmd.c_str(), 50);
		if (WIFI_CMD_STATE_OK == res)
		{
			res = wifi_send_cmd("+CIFSR", 50);
			if (WIFI_CMD_STATE_ROK == res)
			{
				connected_network_name = AP.name;
				return NET_OK;
			}
			break;
		}
	}
	return NET_ERR_WIFI_REGISTER;

	if (WIFI_CMD_STATE_OK == res)
	{
		res = wifi_send_cmd("+CIFSR", 50);
		if (WIFI_CMD_STATE_ROK == res)
		{
			connected_network_name = AP.name;
			wifi_send_cmd("+CIPSTART=\"TCP\",\"www.tmos-arm.com\",80", 50);
			//wifi_send_cmd("+CIPSTART=\"TCP\",\"192.168.147.100\",6112", 50);
			cmd.clear();
			cmd.append("+CIPSEND=");
			cmd.appendf("%d", strlen(message) + 1);
		    wifi_send_cmd(cmd.c_str(), 200);

			// make sure the handle is working if it is open
		    while(rcv_hnd.res < FLG_BUSY)
		    {
				process_input(0, NULL);
		    }

			wifi_sleep(20); //(the recommended value is at least 20 ms)

		    // make sure no URC is coming and the buf is empty
		    if( cmd_state & WIFI_CMD_STATE_STARTED)
		    {
		        if (tsk_wait_signal(rcv_hnd.signal, 8192))
		        {
		    		do
		    		{
		    			process_input(rcv_hnd.signal, NULL);

		    		} while ( (cmd_state & WIFI_CMD_STATE_STARTED) &&
		    				tsk_resume_wait_signal(rcv_hnd.signal) );
		        }
		    }
		    //start clean
		    cmd_state &= (WIFI_CMD_STATE_ROW_STOP | WIFI_CMD_STATE_HND);
		   	row_start = row_end = 0;

		    snd_hnd.tsk_write(message, strlen(message) + 1, WIFI_WRITE_TOT);
			return NET_OK;
		}
	}
	return wifi_net_error(res);
}
Пример #5
0
RES_CODE esp8266_module::process_write(CSocket* sock)
{
	unsigned size;//, newsize, id;
//	unsigned int start_size, write_size, sock_state;
	CSTRING cmd;
	unsigned char snd_pending;


	while(1)
	{
		size = sock->len;
		if(!size)
		{
		    TRACELN1("WIFI: write OK");
			return RES_SIG_OK;
		}
		if(size >1022)
			size = 1022;

		if(sock->sock_state != SOCKET_CONECTED)
			break;

		// Send command
		cmd.format("+CIPSEND=%u,%u", sock->sock_id, size);
	    TRACELN("WIFI: WRITE %d?", size);
	    cmd_state |= WIFI_CMD_STATE_HND;
	    if(wifi_send_cmd(cmd.c_str(), 20) != WIFI_CMD_STATE_RETURNED)
	    {
	    	wifi_net_error(NET_ERR_SOCK_WRITE);
	    	return RES_SIG_ERROR;
	    }


	    // Send data
		snd_pending = '>';
		do
		{
			process_input(rcv_hnd.signal, cmd.c_str(), snd_pending);
			if ( cmd_state >= WIFI_CMD_STATE_HND )
			{
				if ( cmd_state & WIFI_CMD_STATE_HND )
				{
					unsigned int mytime;

					cmd_state &= ~WIFI_CMD_STATE_HND;
					snd_pending = 0;

					rcv_hnd.tsk_start_read(&received_ch, 1);
					mytime = CURRENT_TASK->time;
					tsk_sleep(55); // data sheet recomendation
					if( snd_hnd.tsk_write(sock->src.as_voidptr, size, WIFI_WRITE_TOT) != RES_OK)
						break;
					CURRENT_TASK->time = mytime;

				} else
				{
					if ( cmd_state >= WIFI_CMD_STATE_OK )
						break; // command completed with OK, ERROR ..
				}
			}

		} while(tsk_resume_wait_signal(rcv_hnd.signal));

//	    wifi_on_blink_transfer(this, GPRS_TRANSFER_INDICATOR);

	    //Check the result
	    if(cmd_state & WIFI_CMD_STATE_OK)
	    {
			TRACE1(" done!");
			sock->src.as_byteptr += size;
			sock->len -= size;
			continue;
		}

	    if (cmd_state & WIFI_CMD_STATE_CMES)
	    {
	    	TRACE_ERROR("\r\nWIFI:%s write ERROR", sock->client.task->name);
	    }

    	break;
	}
	wifi_sleep(120);
	wifi_net_error(NET_ERR_SOCK_WRITE);
	return RES_SIG_ERROR;
}
Пример #6
0
void
server_loop2(Authctxt *authctxt)
{
	fd_set *readset = NULL, *writeset = NULL;
	int rekeying = 0, max_fd;
	u_int nalloc = 0;
	double start_time, total_time;

	debug("Entering interactive session for SSH2.");
	start_time = get_current_time();

	signal(SIGCHLD, sigchld_handler);
	child_terminated = 0;
	connection_in = packet_get_connection_in();
	connection_out = packet_get_connection_out();

	if (!use_privsep) {
		signal(SIGTERM, sigterm_handler);
		signal(SIGINT, sigterm_handler);
		signal(SIGQUIT, sigterm_handler);
	}

	notify_setup();

	max_fd = MAX(connection_in, connection_out);
	max_fd = MAX(max_fd, notify_pipe[0]);

	server_init_dispatch();

	for (;;) {
		process_buffered_input_packets();

		rekeying = (xxx_kex != NULL && !xxx_kex->done);

		if (!rekeying && packet_not_very_much_data_to_write())
			channel_output_poll();
		wait_until_can_do_something(&readset, &writeset, &max_fd,
		    &nalloc, 0);

		if (received_sigterm) {
			logit("Exiting on signal %d", (int)received_sigterm);
			/* Clean up sessions, utmp, etc. */
			cleanup_exit(255);
		}

		collect_children();
		if (!rekeying) {
			channel_after_select(readset, writeset);
			if (packet_need_rekeying()) {
				debug("need rekeying");
				xxx_kex->done = 0;
				kex_send_kexinit(xxx_kex);
			}
		}
		process_input(readset);
		if (connection_closed)
			break;
		process_output(writeset);
	}
	collect_children();

	if (readset)
		xfree(readset);
	if (writeset)
		xfree(writeset);

	/* free all channels, no more reads and writes */
	channel_free_all();

	/* free remaining sessions, e.g. remove wtmp entries */
	session_destroy_all(NULL);
	total_time = get_current_time() - start_time;
	logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
	      get_remote_ipaddr(), get_remote_port(),
	      stdin_bytes, fdout_bytes, total_time, stdin_bytes / total_time, 
	      fdout_bytes / total_time);
}
Пример #7
0
int main(int argc, char **argv) {
	setlocale(LC_ALL, ""); // Comment-out on non-Posix systems
	clock_t time_start = clock();
	time_t time_t_start;
	time(&time_t_start);
	argv_0_basename = basename(argv[0]);
	get_usage_string(usage, USAGE_LEN); // This is a big scary string, so build it elsewhere

	//printf("sizeof(cmd_args)=%zd\n", sizeof(cmd_args));
	parse_cmd_args(argc, argv, usage, &cmd_args);

	if (cmd_args.class_algo == EXCHANGE || cmd_args.class_algo == EXCHANGE_BROWN)
		memusage += sizeof(float) * ENTROPY_TERMS_MAX; // We'll build the precomputed entropy terms after reporting memusage

	struct_model_metadata global_metadata;

	// The list of unique words should always include <s>, unknown word, and </s>
	map_update_count(&word_map, UNKNOWN_WORD, 0, 0); // Should always be first
	map_update_count(&word_map, "<s>", 0, 1);
	map_update_count(&word_map, "</s>", 0, 2);

	// Open input
	FILE *in_train_file = stdin;
	if (in_train_file_string)
		in_train_file = fopen(in_train_file_string, "r");
	if (in_train_file == NULL) {
		fprintf(stderr, "%s: Error: Unable to open input file  %s\n", argv_0_basename, in_train_file_string); fflush(stderr);
		exit(15);
	}

	// Process input sentences
	size_t input_memusage = 0;
	const struct_model_metadata input_model_metadata = process_input(cmd_args, in_train_file, &word_map, &initial_bigram_map, &input_memusage);
	memusage += input_memusage;
	fclose(in_train_file);

	clock_t time_input_processed = clock();
	if (cmd_args.verbose >= -1)
		fprintf(stderr, "%s: Corpus processed in %'.2f CPU secs. %'lu lines, %'u types, %'lu tokens, current memusage: %'.1fMB\n", argv_0_basename, (double)(time_input_processed - time_start)/CLOCKS_PER_SEC, input_model_metadata.line_count, input_model_metadata.type_count, input_model_metadata.token_count, (double)memusage / 1048576); fflush(stderr);

	global_metadata.token_count = input_model_metadata.token_count;
	global_metadata.type_count  = map_count(&word_map);

	// Filter out infrequent words, reassign word_id's, and build a mapping from old word_id's to new word_id's
	sort_by_count(&word_map);
	word_id_t * restrict word_id_remap = calloc(sizeof(word_id_t), input_model_metadata.type_count);
	get_ids(&word_map, word_id_remap);
	word_id_t number_of_deleted_words = filter_infrequent_words(cmd_args, &global_metadata, &word_map, word_id_remap);

	// Get list of unique words
	char * * restrict word_list = (char **)malloc(sizeof(char*) * global_metadata.type_count);
	memusage += sizeof(char*) * global_metadata.type_count;
	reassign_word_ids(&word_map, word_list, word_id_remap);
	get_keys(&word_map, word_list);
	sort_by_id(&word_map);


	// Check or set number of classes
	if (cmd_args.num_classes >= global_metadata.type_count) { // User manually set number of classes is too low
		fprintf(stderr, "%s: Error: Number of classes (%u) is not less than vocabulary size (%u).  Decrease the value of --classes\n", argv_0_basename, cmd_args.num_classes, global_metadata.type_count); fflush(stderr);
		exit(3);
	} else if (cmd_args.num_classes == 0) { // User did not manually set number of classes at all
		cmd_args.num_classes = (wclass_t) (sqrt(global_metadata.type_count) * 1.2);
	}

	// Build array of word_counts
	word_count_t * restrict word_counts = malloc(sizeof(word_count_t) * global_metadata.type_count);
	memusage += sizeof(word_count_t) * global_metadata.type_count;
	build_word_count_array(&word_map, word_list, word_counts, global_metadata.type_count);

	// Initialize clusters, and possibly read-in external class file
	wclass_t * restrict word2class = malloc(sizeof(wclass_t) * global_metadata.type_count);
	memusage += sizeof(wclass_t) * global_metadata.type_count;
	init_clusters(cmd_args, global_metadata.type_count, word2class, word_counts, word_list);
	if (initial_class_file != NULL)
		import_class_file(&word_map, word2class, initial_class_file, cmd_args.num_classes); // Overwrite subset of word mappings, from user-provided initial_class_file

	// Remap word_id's in initial_bigram_map
	remap_and_rev_bigram_map(&initial_bigram_map, &new_bigram_map, &new_bigram_map_rev, word_id_remap, map_find_id(&word_map, UNKNOWN_WORD, -1));
	global_metadata.start_sent_id = map_find_id(&word_map, "<s>", -1);; // need this for tallying emission probs
	global_metadata.end_sent_id   = map_find_id(&word_map, "</s>", -1);; // need this for tallying emission probs
	global_metadata.line_count    = map_find_count(&word_map, "</s>"); // Used for calculating perplexity

	if (global_metadata.line_count == 0) {
		fprintf(stderr, "%s: Warning: Number of lines is 0.  Include <s> and </s> in your ngram counts, or perplexity values will be unreliable.\n", argv_0_basename); fflush(stderr);
	}

	//printf("init_bigram_map hash_count=%u\n", HASH_COUNT(initial_bigram_map)); fflush(stdout);
	//printf("new_bigram_map hash_count=%u\n", HASH_COUNT(new_bigram_map)); fflush(stdout);
	free(word_id_remap);
	memusage -= sizeof(word_id_t) * input_model_metadata.type_count;
	delete_all(&word_map); // static
	delete_all_bigram(&initial_bigram_map); // static
	memusage -= input_memusage;

	// Initialize and set word bigram listing
	clock_t time_bigram_start = clock();
	size_t bigram_memusage = 0; size_t bigram_rev_memusage = 0;
	struct_word_bigram_entry * restrict word_bigrams = NULL;
	struct_word_bigram_entry * restrict word_bigrams_rev = NULL;

	if (cmd_args.verbose >= -1)
		fprintf(stderr, "%s: Word bigram listing ... ", argv_0_basename); fflush(stderr);

	#pragma omp parallel sections // Both bigram listing and reverse bigram listing can be done in parallel
	{
		#pragma omp section
		{
			//sort_bigrams(&new_bigram_map); // speeds things up later
			word_bigrams = calloc(global_metadata.type_count, sizeof(struct_word_bigram_entry));
			memusage += sizeof(struct_word_bigram_entry) * global_metadata.type_count;
			bigram_memusage = set_bigram_counts(word_bigrams, new_bigram_map);
			// Copy entries in word_counts to struct_word_bigram_entry.headword_count since that struct entry is already loaded when clustering
			for (word_id_t word = 0; word < global_metadata.type_count; word++)
				word_bigrams[word].headword_count = word_counts[word];
		}

		// Initialize and set *reverse* word bigram listing
		#pragma omp section
		{
			if (cmd_args.rev_alternate) { // Don't bother building this if it won't be used
				//sort_bigrams(&new_bigram_map_rev); // speeds things up later
				word_bigrams_rev = calloc(global_metadata.type_count, sizeof(struct_word_bigram_entry));
				memusage += sizeof(struct_word_bigram_entry) * global_metadata.type_count;
				bigram_rev_memusage = set_bigram_counts(word_bigrams_rev, new_bigram_map_rev);
				// Copy entries in word_counts to struct_word_bigram_entry.headword_count since that struct entry is already loaded when clustering
				for (word_id_t word = 0; word < global_metadata.type_count; word++)
					word_bigrams_rev[word].headword_count = word_counts[word];
			}
		}
	}

	delete_all_bigram(&new_bigram_map);
	delete_all_bigram(&new_bigram_map_rev);
	memusage += bigram_memusage + bigram_rev_memusage;
	clock_t time_bigram_end = clock();
	if (cmd_args.verbose >= -1)
		fprintf(stderr, "in %'.2f CPU secs.  Bigram memusage: %'.1f MB\n", (double)(time_bigram_end - time_bigram_start)/CLOCKS_PER_SEC, (bigram_memusage + bigram_rev_memusage)/(double)1048576); fflush(stderr);

	//print_word_bigrams(global_metadata, word_bigrams, word_list);

	// Build <v,c> counts, which consists of a word followed by a given class
	word_class_count_t * restrict word_class_counts = calloc(1 + cmd_args.num_classes * global_metadata.type_count , sizeof(word_class_count_t));
	if (word_class_counts == NULL) {
		fprintf(stderr,  "%s: Error: Unable to allocate enough memory for <v,c>.  %'.1f MB needed.  Maybe increase --min-count\n", argv_0_basename, ((cmd_args.num_classes * global_metadata.type_count * sizeof(word_class_count_t)) / (double)1048576 )); fflush(stderr);
		exit(13);
	}
	memusage += cmd_args.num_classes * global_metadata.type_count * sizeof(word_class_count_t);
	fprintf(stderr, "%s: Allocating %'.1f MB for word_class_counts: num_classes=%u x type_count=%u x sizeof(w-cl-count_t)=%zu\n", argv_0_basename, (double)(cmd_args.num_classes * global_metadata.type_count * sizeof(word_class_count_t)) / 1048576 , cmd_args.num_classes, global_metadata.type_count, sizeof(word_class_count_t)); fflush(stderr);
	build_word_class_counts(cmd_args, word_class_counts, word2class, word_bigrams, global_metadata.type_count/*, word_list*/);
	//print_word_class_counts(cmd_args, global_metadata, word_class_counts);

	// Build reverse: <c,v> counts: class followed by word.  This and the normal one are both pretty fast, so no need to parallelize this
	word_class_count_t * restrict word_class_rev_counts = NULL;
	if (cmd_args.rev_alternate) { // Don't bother building this if it won't be used
		word_class_rev_counts = calloc(1 + cmd_args.num_classes * global_metadata.type_count , sizeof(word_class_count_t));
		if (word_class_rev_counts == NULL) {
			fprintf(stderr,  "%s: Warning: Unable to allocate enough memory for <v,c>.  %'.1f MB needed.  Falling back to --rev-alternate 0\n", argv_0_basename, ((cmd_args.num_classes * global_metadata.type_count * sizeof(word_class_count_t)) / (double)1048576 )); fflush(stderr);
			cmd_args.rev_alternate = 0;
		} else {
			memusage += cmd_args.num_classes * global_metadata.type_count * sizeof(word_class_count_t);
			fprintf(stderr, "%s: Allocating %'.1f MB for word_class_rev_counts: num_classes=%u x type_count=%u x sizeof(w-cl-count_t)=%zu\n", argv_0_basename, (double)(cmd_args.num_classes * global_metadata.type_count * sizeof(word_class_count_t)) / 1048576 , cmd_args.num_classes, global_metadata.type_count, sizeof(word_class_count_t)); fflush(stderr);
			build_word_class_counts(cmd_args, word_class_rev_counts, word2class, word_bigrams_rev, global_metadata.type_count/*, word_list*/);
		}

	}

	// Calculate memusage for count_arrays
	for (unsigned char i = 1; i <= cmd_args.max_array; i++) {
		memusage += 2 * (powi(cmd_args.num_classes, i) * sizeof(wclass_count_t));
		//printf("11 memusage += %zu (now=%zu) count_arrays\n", 2 * (powi(cmd_args.num_classes, i) * sizeof(wclass_count_t)), memusage); fflush(stdout);
	}

	clock_t time_model_built = clock();
	if (cmd_args.verbose >= -1)
		fprintf(stderr, "%s: Finished loading %'lu tokens and %'u types (%'u filtered) from %'lu lines in %'.2f CPU secs\n", argv_0_basename, global_metadata.token_count, global_metadata.type_count, number_of_deleted_words, global_metadata.line_count, (double)(time_model_built - time_start)/CLOCKS_PER_SEC); fflush(stderr);
	if (cmd_args.verbose >= -1)
		fprintf(stderr, "%s: Approximate memory usage at clustering: %'.1fMB\n", argv_0_basename, (double)memusage / 1048576); fflush(stderr);

	cluster(cmd_args, global_metadata, word_counts, word_list, word2class, word_bigrams, word_bigrams_rev, word_class_counts, word_class_rev_counts);

	// Now print the final word2class mapping
	if (cmd_args.verbose >= 0) {
		FILE *out_file = stdout;
		if (out_file_string)
			out_file = fopen(out_file_string, "w");
		if (out_file == NULL) {
			fprintf(stderr, "%s: Error: Unable to open output file  %s\n", argv_0_basename, out_file_string); fflush(stderr);
			exit(16);
		}
		if (cmd_args.class_algo == EXCHANGE && (!cmd_args.print_word_vectors)) {
			print_words_and_classes(out_file, global_metadata.type_count, word_list, word_counts, word2class, (int)cmd_args.class_offset, cmd_args.print_freqs);
		} else if (cmd_args.class_algo == EXCHANGE && cmd_args.print_word_vectors) {
			print_words_and_vectors(out_file, cmd_args, global_metadata, word_list, word2class, word_bigrams, word_bigrams_rev, word_class_counts, word_class_rev_counts);
		}
		fclose(out_file);
	}

	clock_t time_clustered = clock();
	time_t time_t_end;
	time(&time_t_end);
	double time_secs_total = difftime(time_t_end, time_t_start);
	if (cmd_args.verbose >= -1)
		fprintf(stderr, "%s: Finished clustering in %'.2f CPU seconds.  Total wall clock time was about %lim %lis\n", argv_0_basename, (double)(time_clustered - time_model_built)/CLOCKS_PER_SEC, (long)time_secs_total/60, ((long)time_secs_total % 60)  );

	free(word2class);
	free(word_bigrams);
	free(word_list);
	free(word_counts);
	exit(0);
}
Пример #8
0
void
job_run_dialog::on_idle(wxIdleEvent &) {
  process_input();
}
Пример #9
0
int initialize(void)
{
  //int rc;
  int comPath;                /* path to COMMAND.COM (for COMSPEC/reload) */
  char *newTTY;                 /* what to change TTY to */
  int showinfo;                 /* show initial info only if no command line options */

  int ec;           /* error code */
  unsigned offs;        /* offset into environment segment */

  int cmdlen;         /* length of command line */
  char *cmdline;        /* command line duplicated into heap */
  char *p, *h, *q;
#ifdef FEATURE_CALL_LOGGING
#ifndef INCLUDE_CMD_FDDEBUG
  FILE *f;
#endif
#endif

/* Set up the host environment of COMMAND.COM */

	/* Install the dummy handlers for Criter and ^Break */
	initCBreak();
	setvect(0x23, cbreak_handler);
	setvect(0x24, dummy_criter_handler);

  /* DOS shells patch the PPID to the own PID, how stupid this is, however,
    because then DOS won't terminate them, e.g. when a Critical Error
    occurs that is not detected by COMMAND.COM */

  oldPSP = OwnerPSP;
  atexit(exitfct);
  OwnerPSP = _psp;

	dbg_printmem();
#ifdef DEBUG
	{ void* p;
		if((p = malloc(5*1024)) == 0)
			dprintf(("[MEM: Out of memory allocating test block during INIT]"));
		else free(p);
	}
#endif

#ifdef FEATURE_KERNEL_SWAP_SHELL
	if(kswapInit()) {		/* re-invoked */
		if(kswapLoadStruc()) {
			/* OK, on success we need not really keep the shell trick
				(pretend we are our own parent), which might cause
				problems with beta-software-bugs ;-)
				In fact, KSSF will catch up our crashes and re-invoke
				FreeCOM, probably with the loss of any internal
				settings. */
			  OwnerPSP = oldPSP;
			return E_None;
		}
	}
#endif

  /* Some elder DOSs may not pass an initializied environment segment */
  if (env_glbSeg && !isMCB(SEG2MCB(env_glbSeg)))
    env_setGlbSeg(0);       /* Disable the environment */

/* Now parse the command line parameters passed to COMMAND.COM */
  /* Preparations */
  newTTY = 0;
  comPath = tracemode = 0;
  showinfo = 1;

  /* Because FreeCom should be executed in a DOS3+ compatible
    environment most of the time, it is assumed that its path
    can be determined from the environment.
    This has the advantage that the string area is accessable
    very early in the run.
    The name of the current file is string #0. */
  if((offs = env_string(0, 0)) != 0)    /* OK, environment filled */
    grabComFilename(0, (char far *)MK_FP(env_glbSeg, offs));
  /* After that argv[0] is no longer used and maybe zapped.
  	This also will help, as most programs altering the environment
  	segment externally don't expect a string area. */
  env_nullStrings(0);

  /* Aquire the command line, there are three possible sources:
    1) DOS command line @PSP:0x80 as pascal string,
    2) extended DOS command line environment variable CMDLINE,
      if peekb(PSP, 0x80) == 127,&
    3) MKS command line @ENV:2, if peekb(ENV, 0) == '~'
    	&& peekb(ENV, 1) == '='

    Currently implemented is version #1 only
  */
  cmdlen = peekb(_psp, 0x80);
  if(cmdlen < 0 || cmdlen > 126) {
    error_corrupt_command_line();
    cmdlen = 0;
  }
    /* duplicate the command line into the local address space */
  if((cmdline = malloc(cmdlen + 1)) == 0) {
    error_out_of_memory();  /* Cannot recover from this problem */
    return E_NoMem;
  }
  _fmemcpy((char far*)cmdline, MK_FP(_psp, 0x81), cmdlen);
  cmdline[cmdlen] = '\0';
#ifdef FEATURE_CALL_LOGGING
#ifndef INCLUDE_CMD_FDDEBUG
  if((f = fopen(logFilename, "at")) == 0) {
    fprintf(stderr, "Cannot open logfile: \"%s\"\n", logFilename);
  } else {

  putc('"', f);
  if(ComPath)   /* path to command.com already known */
    fputs(ComPath, f);
  putc('"', f);
  putc(':', f);

  fputs(cmdline, f);
  putc('\n', f);
  fclose(f);
  }
#else
	cmd_fddebug(logFilename);

	dbg_outc('"');
	dbg_outs(ComPath);
	dbg_outc('"');
	dbg_outc(':');
	dbg_outsn(cmdline);
#endif
#endif

  canexit = 1;
  p = cmdline;    /* start of the command line */
  do {
  ec = leadOptions(&p, opt_init, 0);
  if(ec == E_NoOption) {    /* /C or /K */
    assert(p && *p);
    if(!isoption(p)) {
      error_quoted_c_k();
      p = 0;
      break;
    }
    assert(p[1] && strchr("kKcC", p[1]));
    p += 2;   /* p := start of command line to execute */
    break;
  } else if(ec != E_None) {
        showhelp = 1;
    p = 0;
    break;
  }

  assert(p && !isoption(p) && !isspace(*p));
  if(!*p) {
    p = 0;
    break;      /* end of line reached */
  }
  q = unquote(p, h = skip_word(p));
  p = h;      /* Skip this word */
  if(!q) {
    error_out_of_memory();
    p = 0;
    break;
  }
  if(!comPath) {      /* 1st argument */
    grabComFilename(1, (char far*)q);
    comPath = 1;
    free(q);
  } else if(!newTTY) {  /* 2nd argument */
#ifdef INCLUDE_CMD_CTTY
    newTTY = q;
#else
      error_ctty_excluded();
    free(q);
#endif
      } else {
        error_too_many_parameters(q);
        showhelp = 1;
        free(q);
        break;
      }
   } while(1);

   /*
    * Now:
    * + autoexec: AUTOEXEC.BAT file to be executed if /P switch
    *   is enabled; if NULL, use default
    * + comPath: user-defined PATH to COMMAND.COM; if NULL, use
    *   the one from the environment
    * + newTTY: the name of the device to be CTTY'ed; if NULL,
    *   no change
    * + p: pointer to the command to be executed:
    *   *p == 'c' or 'C' --> spawn command, then terminate shell
    *   *p == 'k' or 'K' --> spawn command, then go interactive
    *   &p[1] --> command line, unless the first character is an
    *   argument character
    */

/* Now process the options */

#ifdef INCLUDE_CMD_CTTY
  if (newTTY) {      /* change TTY as early as possible so the caller gets
                          the messages into the correct channel */
    cmd_ctty(newTTY);
    free(newTTY);
  }
#endif

  if(!ComPath) {
    /* FreeCom is unable to find itself --> print error message */
    /* Emergency error */
#undef TEXT_MSG_FREECOM_NOT_FOUND
	puts(TEXT_MSG_FREECOM_NOT_FOUND);
    return E_Useage;
  }

  /* First of all, set up the environment */
    /* If a new valid size is specified, use that */
  env_resizeCtrl |= ENV_USEUMB | ENV_ALLOWMOVE;
  if(newEnvSize > 16 && newEnvSize < 32767)
    env_setsize(0, newEnvSize);

  /* Otherwise the path is placed into the environment */
    /* Set the COMSPEC variable. */
  if(chgEnv("COMSPEC", ComPath)) {		/* keep it silent */
    /* Failed to add this variable, the most likely problem should be that
      the environment is too small --> it is increased and the
      operation is redone */
    env_resize(0, strlen(ComPath) + 10);
    if(chgEnv("COMSPEC", ComPath))
    	chgEnv("COMSPEC",  NULL);	/* Cannot set -> zap an old one */
  }
  	inInit = 0;

	/* Install INT 24 Critical error handler */
	/* Needs the ComPath variable, eventually */
	if(!kswapContext) {
		/* Load the module/context into memory */
		if((kswapContext = modContext()) == 0) {
			error_loading_context();
			return E_NoMem;
		}
#ifdef FEATURE_KERNEL_SWAP_SHELL
		if(swapOnExec != ERROR)
			kswapRegister(kswapContext);
#endif
	}

	ctxtCreate();

	/* re-use the already loaded Module */
	setvect(0x24, (void interrupt(*)())
	 MK_FP(FP_SEG(kswapContext->cbreak_hdlr), kswapContext->ofs_criter));

  if(internalBufLen)
    error_l_notimplemented();
  if(inputBufLen)
    error_u_notimplemented();

  if(tracemode)
    showinfo = 0;

  if (showhelp)
    displayString(TEXT_CMDHELP_COMMAND);

  if ((showhelp || exitflag) && canexit)
    return E_None;

  /* Now the /P option can be processed */
	if(!canexit) {
		char *autoexec;

		autoexec = user_autoexec? user_autoexec: AUTO_EXEC;

		showinfo = 0;
		short_version();

		if(skipAUTOEXEC) {		/* /D option */
			showinfo = 0;
			displayString(TEXT_MSG_INIT_BYPASSING_AUTOEXEC, autoexec);
		} else {
			if(exist(autoexec)) {
#ifdef FEATURE_BOOT_KEYS
				struct REGPACK r;
				int key;

				r.r_ax = 0x3000;	/* Get DOS version & OEM ID */
				intr(0x21, &r);
				if(!tracemode	/* /Y --> F8 on CONFIG.SYS */
				 || ((r.r_bx & 0xff00) == 0xfd00	/* FreeDOS >= build 2025 */
				      && !(r.r_cx > 0x101 || (r.r_bx & 0xff) > 24))) {
					displayString(TEXT_MSG_INIT_BYPASS_AUTOEXEC, autoexec);
					key = cgetchar_timed(3);
					putchar('\n');
				} else key = 0;

				if(key == KEY_F8)
					tracemode = 1;

				if(key == KEY_F5)
					displayString(TEXT_MSG_INIT_BYPASSING_AUTOEXEC, autoexec);
				else
#endif
					process_input(1, autoexec);
			} else {
				if(user_autoexec)
					error_sfile_not_found(user_autoexec);
#ifdef INCLUDE_CMD_DATE
					cmd_date(0);
#endif
#ifdef INCLUDE_CMD_TIME
					cmd_time(0);
#endif
			}
		}

		free(user_autoexec);
	} else {
		assert(user_autoexec == 0);
	}

  /* Now the /C or /K option can be processed */
  if (p)
  {
    process_input(1, p);
    return spawnAndExit;
  }

  /* Don't place something here that must be executed after a /K or /C */

  if (showinfo)
  {
    short_version();
#ifndef DEBUG
    putchar('\n');
    showcmds(0);
    putchar('\n');
#endif
  }

  return E_None;
}
Пример #10
0
// thread main!
int uart_unix_main(void* arg)
{
    dthread_t* self = (dthread_t*) arg;
    dthread_t* other = (dthread_t*) self->arg;
    dmessage_t* mp = NULL;
    dthread_poll_event_t ev, *evp;
    size_t nev;
    dterm_t term;
    uart_ctx_t ctx;
    ErlDrvTermData mp_from;
    ErlDrvTermData mp_ref;
    dthread_t*     mp_source;
    int tmo;
    int r;

    DEBUGF("uart_unix: thread started");

    uart_init(&ctx, self, other);

    dterm_init(&term);

again_tmo:
    tmo = next_timeout(&ctx);
again:
    nev = 0;
    evp = NULL;
    if (ctx.fd >= 0) {
	ev.event = (ErlDrvEvent) ((long)ctx.fd);
	ev.events = 0;
	if ((ctx.option.active != UART_PASSIVE) || ctx.recv)
	    ev.events |= ERL_DRV_READ;
	if (ctx.oq.mesg)
	    ev.events |= ERL_DRV_WRITE;
	if (ev.events) {
	    evp = &ev;
	    nev = 1;
	}
	DEBUGF("ctx.fd=%d, ev.events=%d", ctx.fd, ev.events);

    }

    DEBUGF("uart_unix_main: nev=%d, events=%x, timeout = %d",
	   nev, ev.events, tmo);
    r = dthread_poll(self, evp, &nev, tmo);

    if (r < 0) {
	DEBUGF("uart_unix_main: dthread_poll failed=%d", r);
	goto again_tmo;
    }
    else {
	DEBUGF("uart_unix_main: nev=%d, r=%d", nev, r);

	if (evp && (nev == 1)) {
	    if (evp->revents & ERL_DRV_WRITE)
		process_output(&ctx, self);
	    if (evp->revents & ERL_DRV_READ) {
		while((process_input(&ctx, self, 0) == 1) &&
		      (ctx.option.active != UART_PASSIVE))
		    ;
	    }
	}
	tmo = next_timeout(&ctx);
	DEBUGF("uart_unix_main: timeout = %d", tmo);
	if (ctx.recv) {
	    if (tmo == 0) {
		uart_async_error_am(&ctx, ctx.dport, ctx.caller, am_timeout);
		clear_timeout(&ctx);
		ctx.remain = 0;
	    }
	}
	if (r == 0)
	    goto again;

	// r>0 (number of messages)
	DEBUGF("about to receive message r=%d", r);
	if ((mp = dthread_recv(self, NULL)) == NULL) {
	    DEBUGF("uart_unix_main: message was NULL");
	    goto again;
	}
	mp_from = mp->from;
	mp_ref  = mp->ref;
	mp_source = mp->source;

	switch (mp->cmd) {
	case DTHREAD_STOP:
	    DEBUGF("uart_unix_main: STOP");
	    close_device(&ctx);
	    uart_final(&ctx);
	    dmessage_free(mp);
	    DEBUGF("uart_unix_main: EXIT");
	    dthread_exit(0);
	    break;

	case DTHREAD_OUTPUT: // async send!
	    DEBUGF("uart_unix_main: OUTPUT");
	    if (ctx.fd < 0) {
		dmessage_free(mp);
		goto again;
	    }
	    if (enq_output(&ctx, self, mp, 0) < 0) {
		mp = NULL;
		goto error;
	    }
	    goto again;

	case UART_CMD_CLOSE:
	    DEBUGF("uart_unix_main: CLOSE");
	    close_device(&ctx);
	    goto ok;

	case UART_CMD_SEND: // sync send
	    DEBUGF("uart_unix_main: SEND");
	    if (ctx.fd < 0) goto ebadf;
	    if (enq_output(&ctx, self, mp, mp_from) < 0) {
		mp = NULL;
		goto error;
	    }
	    goto again;

	case UART_CMD_SENDCHAR: // sync send
	    DEBUGF("uart_unix_main: SENDCHAR");
	    if (ctx.fd < 0) goto ebadf;
	    if (enq_output(&ctx, self, mp, mp_from) < 0) {
		mp = NULL;
		goto error;
	    }
	    goto again;

	case UART_CMD_RECV: {  // <<Time:32, Length:32>> Time=0xffffffff=inf
	    uint32_t tm;
	    int len;
	    DEBUGF("uart_unix_main: RECV");
	    if (ctx.fd < 0) goto ebadf;
	    if (ctx.recv) goto ealready;
	    if (mp->used != 8) goto badarg;
	    if (ctx.option.active != UART_PASSIVE) goto badarg;
	    tm = get_uint32((uint8_t*) mp->buffer);
	    len = (int) get_uint32((uint8_t*) (mp->buffer+4));
	    if ((len < 0) || (len > UART_MAX_PACKET_SIZE)) goto badarg;
	    ctx.ref = mp_ref;
	    ctx.caller = mp_from;
	    set_timeout(&ctx, tm);
	    ctx.recv = 1;
	    DEBUGF("recv timeout %lu", tm);
	    process_input(&ctx, self, len);
	    dmessage_free(mp);
	    goto again_tmo;
	}

	case UART_CMD_UNRECV: {  // argument is data to push back
	    uart_buf_push(&ctx.ib, mp->buffer, mp->used);
	    DEBUGF("unrecived %d bytes", ctx.ib.ptr - ctx.ib.ptr_start);
	    if (ctx.option.active != UART_PASSIVE) {
		while((process_input(&ctx, self, 0) == 1) &&
		      (ctx.option.active != UART_PASSIVE))
		    ;
	    }
	    goto ok;
	}

	case UART_CMD_SETOPTS: {
	    uart_com_state_t state  = ctx.state;
	    uart_opt_t       option = ctx.option;
	    uint32_t         sflags = ctx.sflags;

	    // parse & update options in state,option and sflag
	    if (uart_parse_opts(mp->buffer, mp->used,
				&state, &option, &sflags) < 0)
		goto badarg;

	    //  apply the changed values
	    if ((r=apply_opts(&ctx, &state, &option, sflags)) < 0)
		goto error;

	    if (r == 1) {
		while((process_input(&ctx, self, 0) == 1) &&
		      (ctx.option.active != UART_PASSIVE))
		    ;
	    }
	    goto ok;
	}

	case UART_CMD_GETOPTS: {
	    dterm_mark_t m1;
	    dterm_mark_t m2;
	    // {Ref, {ok,List}} || {Ref, {error,Reason}}
	    dterm_tuple_begin(&term, &m1); {
		dterm_uint(&term, mp_ref);
		dterm_tuple_begin(&term, &m2); {
		    dterm_atom(&term, am_ok);
		    if (uart_get_opts(&term, &ctx,(uint8_t*)mp->buffer,mp->used) < 0) {
			dterm_reset(&term);
			goto badarg;
		    }
		}
		dterm_tuple_end(&term, &m2);
	    }
	    dterm_tuple_end(&term, &m1);
	    dthread_port_send_dterm(mp_source, self, mp_from, &term);
	    dterm_reset(&term);
	    dmessage_free(mp);
	    goto again;
	}

	case UART_CMD_GET_MODEM: {
	    dterm_mark_t m1;
	    dterm_mark_t m2;
	    uart_modem_state_t mstate;
	    if (ctx.fd < 0) goto ebadf;
	    if (get_modem_state(ctx.fd, &mstate) < 0) goto error;

	    dterm_tuple_begin(&term, &m1); {
		dterm_uint(&term, mp_ref);
		dterm_tuple_begin(&term, &m2); {
		    dterm_atom(&term, am_ok);
		    modem_state_dterm(&term, mstate);
		}
		dterm_tuple_end(&term, &m2);
	    }
	    dterm_tuple_end(&term, &m1);
	    dthread_port_send_dterm(mp_source, self, mp_from, &term);
	    dterm_reset(&term);
	    dmessage_free(mp);
	    goto again;
	}

	case UART_CMD_SET_MODEM: {
	    uart_modem_state_t mstate;
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 4) goto badarg;
	    mstate = (uart_modem_state_t) get_uint32((uint8_t*) mp->buffer);
	    if (set_modem_state(ctx.fd, mstate, 1) < 0) goto error;
	    goto ok;
	}

	case UART_CMD_CLR_MODEM: {
	    uart_modem_state_t mstate;
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 4) goto badarg;
	    mstate = (uart_modem_state_t) get_uint32((uint8_t*) mp->buffer);
	    if (set_modem_state(ctx.fd, mstate, 0) < 0) goto error;
	    goto ok;
	}

	case UART_CMD_HANGUP: {
	    struct termios tio;
	    int r;
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 0) goto badarg;
	    if ((r = tcgetattr(ctx.fd, &tio)) < 0) {
		INFOF("tcgetattr: error=%s\n", strerror(errno));
		goto badarg;
	    }
	    cfsetispeed(&tio, B0);
	    cfsetospeed(&tio, B0);
	    if ((r = tcsetattr(ctx.fd, TCSANOW, &tio)) < 0) {
		INFOF("tcsetattr: error=%s\n", strerror(errno));
		goto badarg;
	    }
	    goto ok;
	}

	case UART_CMD_BREAK: {
	    int duration;
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 4) goto badarg;
	    duration = (int) get_uint32((uint8_t*) mp->buffer);
	    if (tcsendbreak(ctx.fd, duration) < 0)
		goto error;
	    goto ok;
	}

	case UART_CMD_FLOW:
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 1) goto badarg;
	    switch(mp->buffer[0]) {
	    case 0: r = tcflow(ctx.fd, TCIOFF); break;
	    case 1: r = tcflow(ctx.fd, TCION); break;
	    case 2: r = tcflow(ctx.fd, TCOOFF); break;
	    case 3: r = tcflow(ctx.fd, TCOON); break;
	    default: goto badarg; break;
	    }
	    if (r < 0)
		goto error;
	    goto ok;

	default:
	    goto badarg;
	}
    }

ok:
    dthread_port_send_ok(mp_source, self,  mp_from, mp_ref);
    if (mp) dmessage_free(mp);
    goto again;

ebadf:
    errno = EBADF;
    goto error;
badarg:
    errno = EINVAL;
    goto error;
ealready:
    errno = EALREADY;
    goto error;

error:
    dthread_port_send_error(mp_source, self, mp_from, mp_ref,
			    uart_errno(&ctx));
    if (mp) dmessage_free(mp);
    goto again;
}
Пример #11
0
void
job_run_dialog::on_timer(wxTimerEvent &) {
  process_input();
}
Пример #12
0
/*
/Dump database to a file
*/
int load_database(sqlite3 * db, FILE * infile, int * lineErr){
  int rc = 0;
  process_input(db, infile, lineErr);

  return rc;
}
Пример #13
0
int main (int argc, char *argv[]) {
	char input_file[MAX_DIR] = MATRIX_DIR; 
	char input_index_file[MAX_DIR] = MATRIX_DIR; 
	char input_matrix_file[MAX_DIR] = MATRIX_DIR; 
	char input_matrix_name[MAX_DIR];
	char tmp_module_file[MAX_DIR] = MATRIX_DIR; 
	char final_module_file[MAX_DIR] = MATRIX_DIR; 
	char output_file[MAX_DIR] = MATRIX_DIR;
	char log_file[MAX_DIR] = MATRIX_DIR;
	char answer_file[MAX_DIR] = MATRIX_DIR;
	char prog[MAX_DIR]=BIN_DIR; 
	char mode, prog_option; 
	int i,j, k, l, num_edges, *pnum_edges, num_modules, *pnum_modules, num_answer_modules, *pnum_answer_modules; 
	ModulePtr modules, module, answer_modules, answer_module; 
	char tmp_file[MAX_DIR] = MATRIX_DIR; 
	double M, final_M; 
	int num_vertices, *pnum_vertices, num_lines; 
	int *degrees, total_edges; 
	int rand_num; 
	FILE *fp, *log; 
	time_t t_0, t_1, t, t_last;
	clock_t clo_0, clo_1, clo_last; 
	int elapTicks; 
	double elapMilli, elapSeconds, elapMinutes;  
	char answer_option; 
	double acc_0, acc_1; 
	double th1_up, th1_low, th2_up, th2_low; 
	char suffix[MAX_ATTR_NAME]; 
	char rand_graph_option; 

	if (argc < 3) { 
		fprintf(stderr, "Too few arguments!\n");
		fprintf(stderr, "Usage:\n");
		fprintf(stderr, "<Program Name> input_matrix (tab delimitted (string or index)) program_option (1: MSG.out; 2: SCNewman; 3: testQcut) answer_option (0: no answer; 1: answer) answer_file\n"); 
		exit(EXIT_FAILURE);
	}

	strcat(input_file, argv[1]); 
	strcpy (input_matrix_name, argv[1]); 
	prog_option = atoi(argv[2]); 
	answer_option = atoi(argv[3]); 
	if (answer_option) { 
		if (argc < 4) { 
			fprintf(stderr, "Missing answer file\n"); 
			fprintf(stderr, "Usage:\n");
			fprintf(stderr, "<Program Name> input_matrix (tab delimitted (string or index)) program_option (1: MSG.out; 2: SCNewman; 3: testQcut) answer_option (0: no answer; 1: answer) answer_file\n");
			exit(EXIT_FAILURE);
		}
		strcat(answer_file, argv[4]); 
	}

	strcat(input_index_file, argv[1]); 
	strcat(input_index_file, ".index"); 
	strcat(input_matrix_file, argv[1]); 
	strcat(input_matrix_file, ".matrix"); 

	strcat(output_file, argv[1]); 
	strcat(output_file, "_result_"); 
	strcat(log_file, argv[1]); 
	strcat(log_file, "_"); 

	strcat(final_module_file, argv[1]); 
	strcat(final_module_file, "_result_"); 

	if (prog_option == 1) { 
		strcat (prog, "MSG.out"); 
		strcat (input_matrix_name, "_MSG.out"); 
		strcat(final_module_file, "iNP_MSG"); 
		strcat(output_file, "MSG"); 
		strcat(log_file, "iNP_MSG.log"); 
	} else if (prog_option == 2) { 
		strcat (prog, "do_SCNewman"); 
		strcat (input_matrix_name, "_SCNewman");
		strcat(final_module_file, "iNP_SCNewman"); 
		strcat(output_file, "SCNewman"); 
		strcat(log_file, "iNP_SCNewman.log"); 
	} else if (prog_option == 3) { 
		strcat (prog, "qcut.pl");
		strcat (input_matrix_name, "_qcut"); 
		strcat(final_module_file, "iNP_Qcut"); 
		strcat(output_file, "Qcut"); 
		strcat(log_file, "iNP_Qcut.log"); 
	} else { 
		fprintf(stderr, "<Program Name> input_matrix (tab delimitted (string or index)) mode (0, 1, 2) program_option (1: MSG.out)\n"); 
		fprintf(stderr, "program_option currently allows only 1 - 3 (1: MSG, 2: SC, 3: Qcut)\n"); 
		exit(EXIT_FAILURE); 
	}
	if ((log = fopen(log_file, "w")) == NULL) {
		fprintf(stderr, "\nFailure to write file %s in read mode\n", log_file);
		fflush(NULL);
		return(-1);
	}

	num_vertices = 0; 
	pnum_vertices = &num_vertices;
	num_lines =	process_input(input_file, input_index_file, input_matrix_file, pnum_vertices); 
	degrees = (int *) calloc(num_vertices, sizeof(int))-1;
	total_edges = read_input_matrix(input_matrix_file, num_vertices, degrees); 

	num_modules = 0; 
	pnum_modules = &num_modules; 
	modules = (ModulePtr) malloc(num_vertices * sizeof(ModuleStr)) - 1; 

	time (&t_0); 
	M = partition_network(input_matrix_file, pnum_modules, modules, prog, prog_option); 
	time (&t_1); 

	if ((fp = fopen(output_file, "w")) == NULL) {
		fprintf(stderr, "\nFailure to write file %s in read mode\n", output_file);
		fflush(NULL);
		return(-1);
	}

/* print networks partitioned without iterations */ 
	for (i = 1; i <= num_modules; i ++) { 
		module = modules + i; 
		for (j = 1; j <= module->num_nodes; j ++) { 
			fprintf(fp, "%s\t", (vertices + module->nodes[j])->name); 
		}
		fprintf(fp, "\n");
	}
	fprintf(fp, "%f\n", M); 
	fclose (fp); 

	final_modules = (ModulePtr) malloc(num_vertices * sizeof(ModuleStr)) - 1; 
	num_final_modules = 0; 
	pnum_final_modules = &num_final_modules; 

	//printf ("%s %f\n", output_file, M); 
	rand_num = (int) rand(); 
	for (i = 1; i <= num_modules; i ++) { 
		module = modules + i; 
		iRun(module, num_vertices, prog, input_matrix_name, prog_option); 
	}
	if (num_final_modules) { 
		final_M = calculate_modularity(num_final_modules, final_modules, degrees, total_edges); 
		/* print networks partitioned with iterations */ 
		print_modules(final_module_file, final_M); 
	}
	time (&t_last); 

	fprintf (log, "NP\tnum_modules\t%d\tmodularity\t%f\ttime\t%f\t", num_modules, M, difftime(t_1, t_0)); 
	if (answer_option) { 
		acc_0 = jaccard(answer_file, output_file); 
		fprintf (log, "acc\t%f\n", acc_0); 
	} else { 
		fprintf (log, "\n"); 
	}
	fprintf (log, "iNP\tnum_modules\t%d\tmodularity\t%f\ttime\t%f\t", num_final_modules, final_M, difftime(t_last, t_0)); 
	if (answer_option) { 
		acc_1 = jaccard(answer_file, final_module_file); 
		fprintf (log, "acc\t%f\n", acc_1); 
	} else { 
		fprintf (log, "\n"); 
	}
	fclose (log); 
	
	remove(input_matrix_file); 
	remove(input_index_file); 

	return 0;
}
Пример #14
0
void game_loop( void )
{
   struct timeval last_time;

   gettimeofday( &last_time, NULL );
   current_time = last_time.tv_sec;

   // Main loop 
   while( !mud_down )
   {
      accept_new( control );

      // Primative, yet effective infinite loop catcher. At least that's the idea.
      set_alarm( 30 );
      alarm_section = "game_loop";

      // If no descriptors are present, why bother processing input for them?
      if( dlist.size(  ) > 0 )
         process_input(  );

#if !defined(__CYGWIN__)
#ifdef MULTIPORT
      mud_recv_message(  );
#endif
#endif
#ifdef IMC
      imc_loop(  );
#endif

      // Autonomous game motion. Stops processing when there are no people at all online.
      if( dlist.size(  ) > 0 )
         update_handler(  );

      // Event handling. Will continue to process even with nobody around. Keeps areas fresh this way.
      run_events( current_time );

      // If no descriptors are present, why bother processing output for them?
      if( dlist.size(  ) > 0 )
         process_output(  );

      /*
       * Synchronize to a clock. ( Would have moved this to its own function, but the code REALLY hated that plan.... )
       * Sleep( last_time + 1/PULSE_PER_SECOND - now ).
       * Careful here of signed versus unsigned arithmetic.
       */
      {
         struct timeval now_time;
         long secDelta;
         long usecDelta;

         gettimeofday( &now_time, NULL );
         usecDelta = ( last_time.tv_usec ) - ( now_time.tv_usec ) + 1000000 / sysdata->pulsepersec;
         secDelta = ( last_time.tv_sec ) - ( now_time.tv_sec );
         while( usecDelta < 0 )
         {
            usecDelta += 1000000;
            secDelta -= 1;
         }

         while( usecDelta >= 1000000 )
         {
            usecDelta -= 1000000;
            secDelta += 1;
         }

         if( secDelta > 0 || ( secDelta == 0 && usecDelta > 0 ) )
         {
            struct timeval stall_time;

            stall_time.tv_usec = usecDelta;
            stall_time.tv_sec = secDelta;
            if( select( 0, NULL, NULL, NULL, &stall_time ) < 0 && errno != EINTR )
            {
               perror( "game_loop: select: stall" );
               exit( 1 );
            }
         }
      }
      gettimeofday( &last_time, NULL );
      current_time = last_time.tv_sec;

      // Dunno if it needs to be reset, but I'll do it anyway. End of the loop here. 
      set_alarm( 0 );

      /*
       * This will be the very last thing done here, because if you can't make it through
       * one lousy loop without crashing a second time.....
       */
      sigsegv = false;
   }
   // End of main game loop 
   // Returns back to 'main', and will result in mud shutdown
}
robot_finds_kitten::robot_finds_kitten( const catacurses::window &w )
{
#ifdef __ANDROID__
    input_context ctxt( "IUSE_SOFTWARE_KITTEN" );
#endif

    ret = false;
    char ktile[83] =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#&()*+./:;=?![]{|}y";
    int used_messages[MAXMESSAGES];

    rfkLINES = 20;
    rfkCOLS = 60;

    const int numbogus = 20;
    nummessages = 201;
    empty.x = -1;
    empty.y = -1;
    empty.color = nc_color();
    empty.character = ' ';
    for( int c = 0; c < rfkCOLS; c++ ) {
        for( int c2 = 0; c2 < rfkLINES; c2++ ) {
            rfkscreen[c][c2] = EMPTY;
        }
    }
    /* Create an array to ensure we don't get duplicate messages. */
    for( int c = 0; c < nummessages; c++ ) {
        used_messages[c] = 0;
        bogus_messages[c] = 0;
        bogus[c] = empty;
    }
    /* Now we initialize the various game OBJECTs.
       * Assign a position to the player. */
    robot.x = rand() % rfkCOLS;
    robot.y = rand() % ( rfkLINES - 3 ) + 3;
    robot.character = '#';
    robot.color = c_white;
    rfkscreen[robot.x][robot.y] = ROBOT;

    /* Assign the kitten a unique position. */
    do {
        kitten.x = rand() % rfkCOLS;
        kitten.y = rand() % ( rfkLINES - 3 ) + 3;
    } while( rfkscreen[kitten.x][kitten.y] != EMPTY );

    /* Assign the kitten a character and a color. */
    do {
        kitten.character = ktile[rand() % 82];
    } while( kitten.character == '#' || kitten.character == ' ' );

    do {
        kitten.color = all_colors.get_random();
    } while( kitten.color == c_black );

    rfkscreen[kitten.x][kitten.y] = KITTEN;

    /* Now, initialize non-kitten OBJECTs. */
    for( int c = 0; c < numbogus; c++ ) {
        /* Assign a unique position. */
        do {
            bogus[c].x = rand() % rfkCOLS;
            bogus[c].y = ( rand() % ( rfkLINES - 3 ) ) + 3;
        } while( rfkscreen[bogus[c].x][bogus[c].y] != EMPTY );
        rfkscreen[bogus[c].x][bogus[c].y] = c + 2;

        /* Assign a character. */
        do {
            bogus[c].character = ktile[rand() % 82];
        } while( bogus[c].character == '#' || bogus[c].character == ' ' );

        do {
            bogus[c].color = all_colors.get_random();
        } while( bogus[c].color == c_black );

        /* Assign a unique message. */
        int index = 0;
        do {
            index = rand() % nummessages;
        } while( used_messages[index] != 0 );
        bogus_messages[c] = index;
        used_messages[index] = 1;
    }

    instructions( w );

    werase( w );
    mvwprintz( w, 0, 0, c_white, _( "robotfindskitten v22July2008 - press q to quit." ) );
    for( int c = 0; c < rfkCOLS; c++ ) {
        mvwputch( w, 2, c, BORDER_COLOR, '_' );
    }
    wmove( w, kitten.y, kitten.x );
    draw_kitten( w );

    for( int c = 0; c < numbogus; c++ ) {
        mvwputch( w, bogus[c].y, bogus[c].x, bogus[c].color, bogus[c].character );
    }

    wmove( w, robot.y, robot.x );
    draw_robot( w );
    int old_x = robot.x;
    int old_y = robot.y;

    wrefresh( w );
    /* Now the fun begins. */
    int input = inp_mngr.get_input_event().get_first_input(); // @todo: use input context

    while( input != 'q' && input != 'Q' && input != KEY_ESCAPE ) {
        process_input( input, w );
        if( ret ) {
            break;
        }
        /* Redraw robot, where available */
        if( !( old_x == robot.x && old_y == robot.y ) ) {
            wmove( w, old_y, old_x );
            wputch( w, c_white, ' ' );
            wmove( w, robot.y, robot.x );
            draw_robot( w );
            rfkscreen[old_x][old_y] = EMPTY;
            rfkscreen[robot.x][robot.y] = ROBOT;
            old_x = robot.x;
            old_y = robot.y;
        }
        wrefresh( w );
        // TODO: use input context / rewrite loop so this is only called at one place
        input = inp_mngr.get_input_event().get_first_input();
    }
}
Пример #16
0
int main(int argc, char **argv)
{
    graph_t graph;
    path_t best, candidate, best_candidate;
    int rot_size, rot_start;
    int verbose = 0;

    if ((argc == 2) && (strncmp(argv[1], "-v", sizeof("-v")) == 0)) {
        verbose = 1;
    }
    else if (argc > 1) {
        fprintf(stderr, "\n");
        fprintf(stderr, "  Parâmetros inválidos!\n");
        fprintf(stderr, "\n");
        fprintf(stderr, "Uso: %s [-v]\n", argv[0]);
        fprintf(stderr, " -v     Ativa modo verbose (exibe detalhes da "
                        "execução do algoritmo)\n");
        return EXIT_FAILURE;
    }

    process_input(&graph);
    graph_calculate_distances(&graph);

    path_init(&best, &graph);
    path_find_greedy(&best, 1);

    if (verbose) {
        printf("1o. caminho: ");
        print_path(&best);
    }

    for (rot_size = 2; rot_size < graph.node_count; ++rot_size) {
        if (verbose) {
            printf("\n\n===== Trocando caminhos com tamanho %2d =====\n", rot_size);
        }

        path_copy(&best_candidate, &best);

        for (rot_start = 1; rot_start <= graph.node_count - rot_size; ++rot_start) {
            path_copy(&candidate, &best);
            path_rotate(&candidate, rot_size, rot_start);
            if (verbose) {
                printf("Troca # %3d: ", rot_start);
                print_path(&candidate);
            }

            if (candidate.distance < best_candidate.distance) {
                path_copy(&best_candidate, &candidate);
            }

            path_destroy(&candidate);
        }

        if (best_candidate.distance < best.distance) {
            path_copy(&best, &best_candidate);
        }

        if (verbose) {
            printf("\n   MELHOR  : ");
            print_path(&best);
        }
    }

    if (verbose) {
        printf("\n============================================\n");
    }

    printf("Melhor caminho encontrado:\n");
    print_path(&best);

    path_destroy(&best);
    path_destroy(&best_candidate);
    graph_destroy(&graph);

    return EXIT_SUCCESS;
}
Пример #17
0
int tool_main(int argc, char** argv) {
    SkCommandLineFlags::SetUsage("Render .skp files.");
    SkCommandLineFlags::Parse(argc, argv);

    if (FLAGS_readPath.isEmpty()) {
        SkDebugf(".skp files or directories are required.\n");
        exit(-1);
    }

    if (FLAGS_maxComponentDiff < 0 || FLAGS_maxComponentDiff > 256) {
        SkDebugf("--maxComponentDiff must be between 0 and 256\n");
        exit(-1);
    }

    if (FLAGS_maxComponentDiff != 256 && !FLAGS_validate) {
        SkDebugf("--maxComponentDiff requires --validate\n");
        exit(-1);
    }

    if (FLAGS_writeEncodedImages) {
        if (FLAGS_writePath.isEmpty()) {
            SkDebugf("--writeEncodedImages requires --writePath\n");
            exit(-1);
        }
        if (FLAGS_deferImageDecoding) {
            SkDebugf("--writeEncodedImages is not compatible with --deferImageDecoding\n");
            exit(-1);
        }
    }

    SkString errorString;
    SkAutoTUnref<sk_tools::PictureRenderer> renderer(parseRenderer(errorString,
                                                                   kRender_PictureTool));
    if (errorString.size() > 0) {
        SkDebugf("%s\n", errorString.c_str());
    }

    if (renderer.get() == NULL) {
        exit(-1);
    }

    SkAutoGraphics ag;

    SkString writePath;
    if (FLAGS_writePath.count() == 1) {
        writePath.set(FLAGS_writePath[0]);
    }
    SkString mismatchPath;
    if (FLAGS_mismatchPath.count() == 1) {
        mismatchPath.set(FLAGS_mismatchPath[0]);
    }
    sk_tools::ImageResultsAndExpectations jsonSummary;
    sk_tools::ImageResultsAndExpectations* jsonSummaryPtr = NULL;
    if (FLAGS_writeJsonSummaryPath.count() == 1) {
        jsonSummaryPtr = &jsonSummary;
        if (FLAGS_readJsonSummaryPath.count() == 1) {
            SkASSERT(jsonSummary.readExpectationsFile(FLAGS_readJsonSummaryPath[0]));
        }
    }

    int failures = 0;
    for (int i = 0; i < FLAGS_readPath.count(); i ++) {
        failures += process_input(FLAGS_readPath[i], &writePath, &mismatchPath, *renderer.get(),
                                  jsonSummaryPtr);
    }
    if (failures != 0) {
        SkDebugf("Failed to render %i pictures.\n", failures);
        return 1;
    }
#if GR_CACHE_STATS && SK_SUPPORT_GPU
    if (renderer->isUsingGpuDevice()) {
        GrContext* ctx = renderer->getGrContext();
        ctx->printCacheStats();
    }
#endif

#if GR_GPU_STATS && SK_SUPPORT_GPU
    if (FLAGS_gpuStats && renderer->isUsingGpuDevice()) {
        renderer->getGrContext()->printGpuStats();
    }
#endif

    if (FLAGS_writeJsonSummaryPath.count() == 1) {
        // If there were any descriptions on the command line, insert them now.
        for (int i=0; i<FLAGS_descriptions.count(); i++) {
            SkTArray<SkString> tokens;
            SkStrSplit(FLAGS_descriptions[i], "=", &tokens);
            SkASSERT(tokens.count() == 2);
            jsonSummary.addDescription(tokens[0].c_str(), tokens[1].c_str());
        }
        if (FLAGS_imageBaseGSUrl.count() == 1) {
          jsonSummary.setImageBaseGSUrl(FLAGS_imageBaseGSUrl[0]);
        }
        jsonSummary.writeToFile(FLAGS_writeJsonSummaryPath[0]);
    }
    return 0;
}
Пример #18
0
int tool_main(int argc, char** argv) {
    SetupCrashHandler();
    SkString usage;
    usage.printf("Time drawing .skp files.\n"
                 "\tPossible arguments for --filter: [%s]\n\t\t[%s]",
                 filterTypesUsage().c_str(), filterFlagsUsage().c_str());
    SkCommandLineFlags::SetUsage(usage.c_str());
    SkCommandLineFlags::Parse(argc, argv);

    if (FLAGS_repeat < 1) {
        SkString error;
        error.printf("--repeats must be >= 1. Was %i\n", FLAGS_repeat);
        gLogger.logError(error);
        exit(-1);
    }

    if (FLAGS_logFile.count() == 1) {
        if (!gLogger.SetLogFile(FLAGS_logFile[0])) {
            SkString str;
            str.printf("Could not open %s for writing.\n", FLAGS_logFile[0]);
            gLogger.logError(str);
            // TODO(borenet): We're disabling this for now, due to
            // write-protected Android devices.  The very short-term
            // solution is to ignore the fact that we have no log file.
            //exit(-1);
        }
    }

    SkAutoTDelete<PictureJSONResultsWriter> jsonWriter;
    if (FLAGS_jsonLog.count() == 1) {
        SkASSERT(FLAGS_builderName.count() == 1 && FLAGS_gitHash.count() == 1);
        jsonWriter.reset(SkNEW(PictureJSONResultsWriter(
                        FLAGS_jsonLog[0],
                        FLAGS_builderName[0],
                        FLAGS_buildNumber,
                        FLAGS_timestamp,
                        FLAGS_gitHash[0],
                        FLAGS_gitNumber)));
        gWriter.add(jsonWriter.get());
    }

    gWriter.add(&gLogWriter);


#if SK_ENABLE_INST_COUNT
    gPrintInstCount = true;
#endif
    SkAutoGraphics ag;

    sk_tools::PictureBenchmark benchmark;

    setup_benchmark(&benchmark);

    int failures = 0;
    for (int i = 0; i < FLAGS_readPath.count(); ++i) {
        failures += process_input(FLAGS_readPath[i], benchmark);
    }

    if (failures != 0) {
        SkString err;
        err.printf("Failed to run %i benchmarks.\n", failures);
        gLogger.logError(err);
        return 1;
    }
#if SK_LAZY_CACHE_STATS
    if (FLAGS_trackDeferredCaching) {
        SkDebugf("Total cache hit rate: %f\n",
                 (double) gTotalCacheHits / (gTotalCacheHits + gTotalCacheMisses));
    }
#endif
    gWriter.end();
    return 0;
}
Пример #19
0
Файл: 1080.c Проект: jflyup/POJ
int main()
{
	process_input();
	return 0;
};
Пример #20
0
void
process_args(int argc, char **argv, hydroparam_t * H) {
  int n = 1;
  char donnees[512];
  char config[512];

#if FTI==0
  default_values(H);

#ifdef MPI
  MPI_Comm_size(MPI_COMM_WORLD, &H->nproc);
  MPI_Comm_rank(MPI_COMM_WORLD, &H->mype);
#else
  H->nproc = 1;
  H->mype = 0;
#endif
  while (n < argc) {
    if (strcmp(argv[n], "--help") == 0) {
      usage();
      n++;
      continue;
    }
    if (strcmp(argv[n], "-v") == 0) {
      n++;
      H->prt++;
      continue;
    }
    if (strcmp(argv[n], "-i") == 0) {
      n++;
      strncpy(donnees, argv[n], 512);
      donnees[511] = 0;         // security
      n++;
      continue;
    }
    if (strcmp(argv[n], "-c") == 0) {
      n++;
      fprintf(stderr, "FTI is not available\n");
      n++;
      continue;
    }
    fprintf(stderr, "Key %s is unkown\n", argv[n]);
    n++;
  }
  if (donnees != NULL) {
    process_input(donnees, H);
  } else {
    fprintf(stderr, "Option -i is missing\n");
    exit(1);
  }
#endif
#if FTI>0
  H->prt=0;
  default_values(H);

  while (n < argc) {
    if (strcmp(argv[n], "--help") == 0) {
      usage();
      n++;
      continue;
    }
    if (strcmp(argv[n], "-v") == 0) {
      n++;
      H->prt++;
      continue;
    }
    if (strcmp(argv[n], "-i") == 0) {
      n++;
      strncpy(donnees, argv[n], 512);
      donnees[511] = 0;         // security
      n++;
      continue;
    }
    if (strcmp(argv[n], "-c") == 0) {
      n++;
      strncpy(config, argv[n], 512);
      config[511] = 0;         // security
      n++;
      continue;
      }
    fprintf(stderr, "Key %s is unkown\n", argv[n]);
    n++;
  }
  if (config != NULL) {
#ifdef MPI
    //FTI initialization
    FTI_Init(config, MPI_COMM_WORLD);
#else
    fprintf(stderr, "FTI need MPI\n", argv[n]);
#endif
  } else {
    fprintf(stderr, "Option -c is missing\n");
    exit(1);
  }
  default_values(H);

#ifdef MPI
  MPI_Comm_size(FTI_COMM_WORLD, &H->nproc);
  MPI_Comm_rank(FTI_COMM_WORLD, &H->mype);
#else
  H->nproc = 1;
  H->mype = 0;
#endif
  if (donnees != NULL) {
    process_input(donnees, H);
  } else {
    fprintf(stderr, "Option -i is missing\n");
    exit(1);
  }
#endif

  H->globnx = H->nx;
  H->globny = H->ny;
  H->box[XMIN_BOX] = 0;
  H->box[XMAX_BOX] = H->nx;
  H->box[YMIN_BOX] = 0;
  H->box[YMAX_BOX] = H->ny;

#ifdef MPI
  if (H->nproc > 1) {
#if FTI==0
    MPI_Barrier(MPI_COMM_WORLD);
#endif
#if FTI>0
    MPI_Barrier(FTI_COMM_WORLD);
#endif
    // first pass : determin our actual sub problem size
    CalcSubSurface(0, H->globnx, 0, H->globny, 0, H->nproc - 1, 0, H->box, H->mype, 0);
    // second pass : determin our neighbours
    CalcSubSurface(0, H->globnx, 0, H->globny, 0, H->nproc - 1, 0, H->box, H->mype, 1);

    H->nx = H->box[XMAX_BOX] - H->box[XMIN_BOX];
    H->ny = H->box[YMAX_BOX] - H->box[YMIN_BOX];
    printf("[%4d/%4d] x=%4d X=%4d y=%4d Y=%4d / u=%4d d=%4d l=%4d r=%4d \n", H->mype, H->nproc, H->box[XMIN_BOX], H->box[XMAX_BOX], H->box[YMIN_BOX], H->box[YMAX_BOX], H->box[UP_BOX], H->box[DOWN_BOX], H->box[LEFT_BOX], H->box[RIGHT_BOX]);

    if (H->nx <= 0) {
      printf("Decomposition not suited for this geometry along X: increase nx or change number of procs\n");
    }

    if (H->ny <= 0) {
      printf("Decomposition not suited for this geometry along Y: increase ny or change number of procs\n");
    }

    if (H->nx == 0 || H->ny == 0) {
#if FTI==0
      MPI_Abort(MPI_COMM_WORLD, 123);
#endif
#if FTI>0
      MPI_Abort(FTI_COMM_WORLD, 123);
#endif
    }

    // adapt the boundary conditions 
    if (H->box[LEFT_BOX] != -1) {
      H->boundary_left = 0;
    }
    if (H->box[RIGHT_BOX] != -1) {
      H->boundary_right = 0;
    }
    if (H->box[DOWN_BOX] != -1) {
      H->boundary_down = 0;
    }
    if (H->box[UP_BOX] != -1) {
      H->boundary_up = 0;
    }
  }
  fflush(stdout);
#endif

  if (H->nxystep == -1) {
    // default = full slab
    H->nxystep = (H->nx < H->ny) ? H->nx: H->ny;
  } else {
    if (H->nxystep > H->nx) H->nxystep = H->nx;
    if (H->nxystep > H->ny) H->nxystep = H->ny;
  }

  // small summary of the run conditions
  if (H->mype == 0) {
    printf("+-------------------+\n");
    printf("|GlobNx=%-7d     |\n", H->globnx);
    printf("|GlobNy=%-7d     |\n", H->globny);
    printf("|nx=%-7d         |\n", H->nx);
    printf("|ny=%-7d         |\n", H->ny);
    printf("|nxystep=%-7d    |\n", H->nxystep);
    printf("|tend=%-10.3f    |\n", H->tend);
    printf("|nstepmax=%-7d   |\n", H->nstepmax);
    printf("|noutput=%-7d    |\n", H->noutput);
    printf("|dtoutput=%-10.3f|\n", H->dtoutput);
    printf("+-------------------+\n");
  }
}
Пример #21
0
int tool_main(int argc, char** argv) {
    SkCommandLineFlags::SetUsage("Render .skp files.");
    SkCommandLineFlags::Parse(argc, argv);

    if (FLAGS_readPath.isEmpty()) {
        SkDebugf(".skp files or directories are required.\n");
        exit(-1);
    }

    if (FLAGS_maxComponentDiff < 0 || FLAGS_maxComponentDiff > 256) {
        SkDebugf("--maxComponentDiff must be between 0 and 256\n");
        exit(-1);
    }

    if (FLAGS_maxComponentDiff != 256 && !FLAGS_validate) {
        SkDebugf("--maxComponentDiff requires --validate\n");
        exit(-1);
    }

    if (FLAGS_clone < 0) {
        SkDebugf("--clone must be >= 0. Was %i\n", FLAGS_clone);
        exit(-1);
    }

    if (FLAGS_writeEncodedImages) {
        if (FLAGS_writePath.isEmpty()) {
            SkDebugf("--writeEncodedImages requires --writePath\n");
            exit(-1);
        }
        if (FLAGS_deferImageDecoding) {
            SkDebugf("--writeEncodedImages is not compatible with --deferImageDecoding\n");
            exit(-1);
        }
    }

    SkString errorString;
    SkAutoTUnref<sk_tools::PictureRenderer> renderer(parseRenderer(errorString,
                                                                   kRender_PictureTool));
    if (errorString.size() > 0) {
        SkDebugf("%s\n", errorString.c_str());
    }

    if (renderer.get() == NULL) {
        exit(-1);
    }

    SkAutoGraphics ag;

    SkString outputDir;
    if (FLAGS_writePath.count() == 1) {
        outputDir.set(FLAGS_writePath[0]);
    }
    sk_tools::ImageResultsSummary jsonSummary;
    sk_tools::ImageResultsSummary* jsonSummaryPtr = NULL;
    if (FLAGS_writeJsonSummaryPath.count() == 1) {
        jsonSummaryPtr = &jsonSummary;
    }

    int failures = 0;
    for (int i = 0; i < FLAGS_readPath.count(); i ++) {
        failures += process_input(FLAGS_readPath[i], &outputDir, *renderer.get(), jsonSummaryPtr);
    }
    if (failures != 0) {
        SkDebugf("Failed to render %i pictures.\n", failures);
        return 1;
    }
#if SK_SUPPORT_GPU
#if GR_CACHE_STATS
    if (renderer->isUsingGpuDevice()) {
        GrContext* ctx = renderer->getGrContext();
        ctx->printCacheStats();
#ifdef SK_DEVELOPER
        ctx->dumpFontCache();
#endif
    }
#endif
#endif
    if (FLAGS_writeJsonSummaryPath.count() == 1) {
        jsonSummary.writeToFile(FLAGS_writeJsonSummaryPath[0]);
    }
    return 0;
}
Пример #22
0
void run_in_loop(){
	process_input();
	refresh(); // refreshes curses window
}
Пример #23
0
NET_CODE esp8266_module::wifi_esp8266_socket_open(CSocket* sock)
{
	unsigned int sid;
	sock_mode_t* mode;

	RES_CODE res;
	const char* cmd = "+CIPSTATUS";
	unsigned int sig=0;
	CSTRING msg_list("\r\n");
	uint32_t index=1;

	cmd_state |= WIFI_CMD_STATE_ROW_STOP;
	res = wifi_send_cmd(cmd, 15);
	cmd_state &= ~WIFI_CMD_STATE_ROW_STOP;

	do
	{
		if(sig)
		{
			process_input(sig, cmd);
			res = cmd_state;
		}

		if (res >= WIFI_CMD_STATE_OK)
			break;

		if(res & WIFI_CMD_STATE_RETURNED)
		{
			cmd_state = res & ~WIFI_CMD_STATE_RETURNED;
			msg_list.appendf("%u:%s\r\n", index++, buf);
			row_start = 0;
			row_end = 0;
		}

		sig = tsk_resume_wait_signal(rcv_hnd.signal);
	} while(sig);

//	if(cmd_state & WIFI_CMD_STATE_OK)
//		TRACE1(msg_list.c_str());

	mode = (sock_mode_t*)sock->mode.as_voidptr;
	if(mode )
	{
		if (  (mode->sock_type == IP_SOCKET_UDP && mode->port)
			||(mode->sock_type == IP_SOCKET_TCP) )
		{
			for(sid=0; sid < WIFI_ESP8266_MAX_SOCKETS; sid++)
			{
				if(NULL == alloc_sockets[sid])
				{
					sock->sock_id = sid;
					sock->sock_state = SOCKET_OPEN;
					alloc_sockets[sid] = sock;
#if USE_GPRS_LISTEN
					if (mode->sock_type == IP_SOCKET_UDP)
						listen_ports[sid] = mode->port;
					accept_id[sid] = GPRS_LEON_MAX_SOCKETS;
#endif
					used_sockets++;
//					msg_list.format("\r\nWIFI:%s sock open %d.", sock->client.task->name, sid);
//					TRACE1(msg_list.c_str());
					return NET_OK;
				}
			}
		}
	}
	TRACE_WIFI_ERROR("\r\nWIFI:%s create socket ERROR", sock->client.task->name);
	return wifi_net_error(NET_ERR_SOCK_CREATE);

}
Пример #24
0
int initialize(void)
{
  int comPath;                /* path to COMMAND.COM (for COMSPEC/reload) */
  char *newTTY;                 /* what to change TTY to */
  int showinfo;                 /* show initial info only if no command line options */
  int key;

  int ec;           /* error code */
  unsigned offs;        /* offset into environment segment */

  int cmdlen;         /* length of command line */
  char *cmdline;        /* command line duplicated into heap */
  char *p, *h, *q;
#ifdef FEATURE_CALL_LOGGING
  FILE *f;
#endif

/* Set up the host environment of COMMAND.COM */
	atexit(exitfct);

	if(modAttach()) {		/* Attach to any already loaded module */
		/* successfully attached --> no further processing of
			command line required as this instance was respawned by
			Stub module --> restore session */
		sessionLoad();
		return E_None;
	}

	/* Prepare creating a new instance of FreeCOM */
	/* Install the dummy handlers of CRITER and ^Break Catcher */
	/* Though if the modules are already loaded, they are used right now */
	modPreload();		/* activate dummies unless already attached */

  /* Some elder DOSs may not pass an initialzied environment segment */
  if (env_glbSeg && !isMCB(SEG2MCB(env_glbSeg)))
    env_setGlbSeg(0);       /* Disable the environment */

/* Now parse the command line parameters passed to COMMAND.COM */
  /* Preparations */
  newTTY = NULL;
  comPath = tracemode = 0;
  showinfo = 1;

  /* Because FreeCom should be executed in a DOS3+ compatible
    environment most of the time, it is assumed that its path
    can be determined from the environment.
    This has the advantage that the string area is accessable
    very early in the run.
    The name of the current file is string #0. */
  if((offs = env_string(0, 0)) != 0)    /* OK, environment filled */
    grabComFilename(0, (char far *)MK_FP(env_glbSeg, offs));

		/* Maybe an anchessor has an absolute path */
	sessionInherit();

  /* Aquire the command line, there are three possible sources:
    1) DOS command line @PSP:0x80 as pascal string,
    2) extended DOS command line environment variable CMDLINE,
      if peekb(PSP, 0x80) == 127,&
    3) MKS command line @ENV:2, if peekb(ENV, 0) == '~'

    Currently implemented is version #1 only
  */
  cmdlen = peekb(_psp, 0x80);
  if(cmdlen < 0 || cmdlen > 126) {
    error_corrupt_command_line();
    cmdlen = 0;
  }
    /* duplicate the command line into the local address space */
  if((cmdline = malloc(cmdlen + 1)) == NULL) {
    error_out_of_memory();  /* Cannot recover from this problem */
    return E_NoMem;
  }
  _fmemcpy((char far*)cmdline, MK_FP(_psp, 0x81), cmdlen);
  cmdline[cmdlen] = '\0';
#ifdef FEATURE_CALL_LOGGING
  if((f = fopen(logFilename, "at")) == NULL) {
    fprintf(stderr, "Cannot open logfile: \"%s\"\n", logFilename);
    exit(125);
  }

  putc('"', f);
  if(ComPath)   /* path to command.com already known */
    fputs(ComPath, f);
  putc('"', f);
  putc(':', f);

  fputs(cmdline, f);
  putc('\n', f);
  fclose(f);
#endif

  p = cmdline;    /* start of the command line */
  do {
  ec = leadOptions(&p, opt_init, NULL);
  if(ec == E_NoOption) {    /* /C or /K */
    assert(p && *p);
    if(!isoption(p)) {
      error_quoted_c_k();
      p = NULL;
      break;
    }
    assert(p[1] && strchr("kKcC", p[1]));
    p += 2;   /* p := start of command line to execute */
    break;
  } else if(ec != E_None) {
        showhelp = 1;
    p = NULL;
    break;
  }

  assert(p && !isoption(p) && !isspace(*p));
  if(!*p) {
    p = NULL;
    break;      /* end of line reached */
  }
  q = unquote(p, h = skip_word(p));
  p = h;      /* Skip this word */
  if(!q) {
    error_out_of_memory();
    p = NULL;
    break;
  }
  if(!comPath) {      /* 1st argument */
    grabComFilename(1, (char far*)q);
    comPath = 1;
    free(q);
  } else if(!newTTY) {  /* 2nd argument */
#ifdef INCLUDE_CMD_CTTY
    newTTY = q;
#else
      error_ctty_excluded();
    free(q);
#endif
      } else {
        error_too_many_parameters(q);
        showhelp = 1;
        free(q);
        break;
      }
   } while(1);

   /*
    * Now:
    * + autoexec: AUTOEXEC.BAT file to be executed if /P switch
    *   is enabled; if NULL, use default
    * + comPath: user-defined PATH to COMMAND.COM; if NULL, use
    *   the one from the environment
    * + newTTY: the name of the device to be CTTY'ed; if NULL,
    *   no change
    * + p: pointer to the command to be executed:
    *   *p == 'c' or 'C' --> spawn command, then terminate shell
    *   *p == 'k' or 'K' --> spawn command, then go interactive
    *   &p[1] --> command line, unless the first character is an
    *   argument character
    */

/* Now process the options */

#ifdef INCLUDE_CMD_CTTY
  if (newTTY) {                   /* change TTY as early as possible so the caller gets
                                   the messages into the correct channel */
    cmd_ctty(newTTY);
    free(newTTY);
  }
#endif

  if(!ComPath) {
    /* FreeCom is unable to find itself --> print error message */
    /* Emergency error */
    puts("You must specify the complete path to " COM_NAME);
    puts("as the first argument of COMMAND,");
    puts("for instance: C:\\FDOS");
    return E_Useage;
  }

  /* First of all, set up the environment */
    /* If a new valid size is specified, use that */
  env_resizeCtrl |= ENV_USEUMB | ENV_ALLOWMOVE;
  if(newEnvSize > 16 && newEnvSize < 32767)
    env_setsize(0, newEnvSize);

  /* Otherwise the path is placed into the environment */
  if (chgEnv("COMSPEC", ComPath)) {
    /* Failed to add this variable, the most likely problem should be that
      the environment is too small --> it is increased and the
      operation is redone */
    env_resize(0, strlen(ComPath) + 10);
    if (chgEnv("COMSPEC", ComPath))
    error_env_var("COMSPEC");
  }

  /* Install the resident portion(s)
  	Now that the name of the executeable is known, they can be found
  	definitely */
 	modLoad(); 		/* Load any module unless already attached to */
 	if(!modAttach()) {	/* Attach to the loaded modules */
 		error_missing_modules();
 		return E_Exit;
 	}


  if(internalBufLen)
    error_l_notimplemented();
  if(inputBufLen)
    error_u_notimplemented();

  if(tracemode)
    showinfo = 0;

  if (showhelp)
    displayString(TEXT_CMDHELP_COMMAND);

  if ((showhelp || exitflag) && canexit)
    return E_None;

  /* Now the /P option can be processed */
  if (!canexit)
  {
    char *autoexec;

    autoexec = user_autoexec? user_autoexec: AUTO_EXEC;

    showinfo = 0;
    short_version();

    /* JP: changed so that if autoexec does not exist, then don't ask
       to trace or bypass.
     */
    if (exist(autoexec))
    {
      printf("\nPress F8 for trace mode, or F5 to bypass %s... ", autoexec);
      key = WaitForFkeys();
      putchar('\n');

      if (key == KEY_F8)
      {
        tracemode = 1;
      }

      if (key == KEY_F5)
      {
        printf("Bypassing %s\n", autoexec);
      }
      else
        process_input(1, autoexec);
    }
    else
    {
      if(user_autoexec)
        printf("%s not found.\n", autoexec);
#ifdef INCLUDE_CMD_DATE
      cmd_date(NULL);
#endif
#ifdef INCLUDE_CMD_TIME
      cmd_time(NULL);
#endif
    }

    free(user_autoexec);
  }
  else
  {
    assert(user_autoexec == NULL);
  }

  /* Now the /C or /K option can be processed */
  if (p)
  {
    process_input(1, p);
    return spawnAndExit;
  }

  /* Don't place something here that must be executed after a /K or /C */

  if (showinfo)
  {
    short_version();
    putchar('\n');
    showcmds(NULL);
    putchar('\n');
  }

  return E_None;
}
Пример #25
0
// If an input line begins with "." then invoke this routine to
// process that line.
// Return 1 to exit and 0 to continue.
static int do_meta_command(char *zLine, struct callback_data *p){
	int i=1;
	int nArg=0;
	int n, c;
	int rc=0;
	char *azArg[50];

	// Parse the input line into tokens.
	while( zLine[i] && nArg<ArraySize(azArg) ){
		while( isspace(zLine[i]) ){ i++; }
		if( zLine[i]==0 ) break;
		if( zLine[i]=='\'' || zLine[i]=='"' ){
			int delim=zLine[i++];
			azArg[nArg++]=&zLine[i];
			while( zLine[i] && zLine[i]!=delim ){ i++; }
			if( zLine[i]==delim ){
				zLine[i++]=0;
			}
		}else{
      			azArg[nArg++]=&zLine[i];
      			while( zLine[i] && !isspace(zLine[i]) ){ i++; }
      			if( zLine[i] ) zLine[i++]=0;
    		}
  	}

	// Process the input line.
	if( nArg==0 ) return rc;
	n=strlen(azArg[0]);
	c=azArg[0][0];
	if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
		struct callback_data data;
		char *zErrMsg=0;
		open_db(p);
		memcpy(&data, p, sizeof(data));
		data.showHeader=1;
		data.mode=MODE_Column;
		data.colWidth[0]=3;
		data.colWidth[1]=15;
		data.colWidth[2]=58;
		sqlite_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
		if( zErrMsg ) {
			fprintf(stderr,"Error: %s\n", zErrMsg);
			sqlite_freemem(zErrMsg);
		}
	} else if( c=='d' && strncmp(azArg[0], "dump", n)==0 ) {
			char *zErrMsg=0;
			open_db(p);
			fprintf(p->out, "BEGIN TRANSACTION;\n");
			if( nArg==1 ) {
				sqlite_exec(p->db,
						"SELECT name, type, sql FROM sqlite_master "
						"WHERE type!='meta' AND sql NOT NULL "
						"ORDER BY substr(type,2,1), rowid",
						dump_callback, p, &zErrMsg
				);
			} else {
				int i;
				for(i=1; i<nArg && zErrMsg==0; i++) {
					sqlite_exec_printf(p->db,
								"SELECT name, type, sql FROM sqlite_master "
								"WHERE tbl_name LIKE '%q' AND type!='meta' AND sql NOT NULL "
								"ORDER BY substr(type,2,1), rowid",
								dump_callback, p, &zErrMsg, azArg[i]
					);
			}
		}
		if( zErrMsg ){
      			fprintf(stderr,"Error: %s\n", zErrMsg);
			sqlite_freemem(zErrMsg);
		} else {
			fprintf(p->out, "COMMIT;\n");
		}
	} else if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ) {
		int j;
		char *z=azArg[1];
		int val=atoi(azArg[1]);
		for(j=0; z[j]; j++){
			if( isupper(z[j]) ) z[j]=tolower(z[j]);
		}
		if( strcmp(z,"on")==0 ) {
			val=1;
		} else if( strcmp(z,"yes")==0 ) {
			val=1;
		}
		p->echoOn=val;
	} else if( c=='e' && strncmp(azArg[0], "exit", n)==0 ) {
		rc=1;
	} else if( c=='e' && strncmp(azArg[0], "explain", n)==0 ) {
		int j;
		char *z=nArg>=2 ? azArg[1] : "1";
		int val=atoi(z);
		for(j=0; z[j]; j++){
			if( isupper(z[j]) ) z[j]=tolower(z[j]);
		}
		if( strcmp(z,"on")==0 ){
			val=1;
		} else if( strcmp(z,"yes")==0 ){
			val=1;
		}
		if(val == 1) {
			if(!p->explainPrev.valid) {
				p->explainPrev.valid=1;
				p->explainPrev.mode=p->mode;
				p->explainPrev.showHeader=p->showHeader;
				memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
			}
			/* We could put this code under the !p->explainValid
			** condition so that it does not execute if we are already in
			** explain mode. However, always executing it allows us an easy
			** was to reset to explain mode in case the user previously
			** did an .explain followed by a .width, .mode or .header
			** command.
			*/
			p->mode=MODE_Column;
			p->showHeader=1;
			memset(p->colWidth,0,ArraySize(p->colWidth));
			p->colWidth[0]=4;
			p->colWidth[1]=12;
			p->colWidth[2]=10;
			p->colWidth[3]=10;
			p->colWidth[4]=35;
		} else if (p->explainPrev.valid) {
			p->explainPrev.valid=0;
			p->mode=p->explainPrev.mode;
			p->showHeader=p->explainPrev.showHeader;
			memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
		}
	} else if( c=='h' && (strncmp(azArg[0], "header", n)==0 || strncmp(azArg[0], "headers", n)==0 )&& nArg>1 ){
		int j;
		char *z=azArg[1];
		int val=atoi(azArg[1]);
		for(j=0; z[j]; j++){
			if( isupper(z[j]) ) z[j]=tolower(z[j]);
		}
		if( strcmp(z,"on")==0 ){
			val=1;
		}else if( strcmp(z,"yes")==0 ){
			val=1;
		}
		p->showHeader=val;
	} else if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
		fprintf(stderr,zHelp);
	}else if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg>1 ){
		struct callback_data data;
		char *zErrMsg=0;
		open_db(p);
		memcpy(&data, p, sizeof(data));
		data.showHeader=0;
		data.mode=MODE_List;
		sqlite_exec_printf(p->db,
					"SELECT name FROM sqlite_master "
					"WHERE type='index' AND tbl_name LIKE '%q' "
					"UNION ALL "
					"SELECT name FROM sqlite_temp_master "
					"WHERE type='index' AND tbl_name LIKE '%q' "
					"ORDER BY 1",
					callback, &data, &zErrMsg, azArg[1], azArg[1]
		);
		if( zErrMsg ){
			fprintf(stderr,"Error: %s\n", zErrMsg);
			sqlite_freemem(zErrMsg);
		}
	} else if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg>=2 ){
		int n2=strlen(azArg[1]);
		if( strncmp(azArg[1],"line",n2)==0 || strncmp(azArg[1],"lines",n2)==0 ){
			p->mode=MODE_Line;
		}else if( strncmp(azArg[1],"column",n2)==0 || strncmp(azArg[1],"columns",n2)==0 ){
			p->mode=MODE_Column;
		}else if( strncmp(azArg[1],"list",n2)==0 ){
			p->mode=MODE_List;
		}else if( strncmp(azArg[1],"html",n2)==0 ){
			p->mode=MODE_Html;
		}else if( strncmp(azArg[1],"insert",n2)==0 ){
			p->mode=MODE_Insert;
			if( nArg>=3 ){
				set_table_name(p, azArg[2]);
			}else{
				set_table_name(p, "table");
			}
		}else {
			fprintf(stderr,"mode should be on of: column html insert line list\n");
		}
	}else if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
		sprintf(p->nullvalue, "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
	}else if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
		if( p->out!=stdout ){
			fclose(p->out);
		}
		if( strcmp(azArg[1],"stdout")==0 ){
			p->out=stdout;
			strcpy(p->outfile,"stdout");
 		}else{
			p->out=fopen(azArg[1], "wb");
			if( p->out==0 ){
				fprintf(stderr,"can't write to \"%s\"\n", azArg[1]);
				p->out=stdout;
			} else {
				strcpy(p->outfile,azArg[1]);
			}
		}
	} else if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
		if( nArg >= 2) {
			strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
		}
		if( nArg >= 3) {
			strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
		}
	}else if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
		rc=1;
	}else if( c=='r' && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
		FILE *alt=fopen(azArg[1], "rb");
		if( alt==0 ){
			fprintf(stderr,"can't open \"%s\"\n", azArg[1]);
		} else {
			process_input(p, alt);
			fclose(alt);
		}
	} else if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
		struct callback_data data;
		char *zErrMsg=0;
		open_db(p);
		memcpy(&data, p, sizeof(data));
		data.showHeader=0;
		data.mode=MODE_Semi;
		if( nArg>1 ) {
			extern int sqliteStrICmp(const char*,const char*);
      			if(sqliteStrICmp(azArg[1],"sqlite_master")==0 ) {
				char *new_argv[2], *new_colv[2];
				new_argv[0]=	"CREATE TABLE sqlite_master (\n"
						"  type text,\n"
						"  name text,\n"
						"  tbl_name text,\n"
						"  rootpage integer,\n"
						"  sql text\n"
						")";
				new_argv[1]=0;
				new_colv[0]="sql";
				new_colv[1]=0;
				callback(&data, 1, new_argv, new_colv);
			} else if( sqliteStrICmp(azArg[1],"sqlite_temp_master")==0 ) {
				char *new_argv[2], *new_colv[2];
				new_argv[0]=	"CREATE TEMP TABLE sqlite_temp_master (\n"
						"  type text,\n"
						"  name text,\n"
						"  tbl_name text,\n"
						"  rootpage integer,\n"
						"  sql text\n"
						")";
				new_argv[1]=0;
				new_colv[0]="sql";
				new_colv[1]=0;
				callback(&data, 1, new_argv, new_colv);
			} else {
				sqlite_exec_printf(p->db,
						"SELECT sql FROM "
						"  (SELECT * FROM sqlite_master UNION ALL"
						"   SELECT * FROM sqlite_temp_master) "
						"WHERE tbl_name LIKE '%q' AND type!='meta' AND sql NOTNULL "
						"ORDER BY substr(type,2,1), name",
						callback, &data, &zErrMsg, azArg[1]);
			}
   	 	} else {
			sqlite_exec(p->db,
					"SELECT sql FROM "
					"  (SELECT * FROM sqlite_master UNION ALL"
					"   SELECT * FROM sqlite_temp_master) "
					"WHERE type!='meta' AND sql NOTNULL "
					"ORDER BY substr(type,2,1), name",
					callback, &data, &zErrMsg
			);
		}
		if( zErrMsg ){
			fprintf(stderr,"Error: %s\n", zErrMsg);
			sqlite_freemem(zErrMsg);
		}
	} else if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
		sprintf(p->separator, "%.*s", (int)ArraySize(p->separator)-1, azArg[1]);
	}else if( c=='s' && strncmp(azArg[0], "show", n)==0){
		int i;
		fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
		fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
		fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
		fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
		fprintf(p->out,"%9.9s: %s\n","nullvalue", p->nullvalue);
		fprintf(p->out,"%9.9s: %s\n","output",strlen(p->outfile) ? p->outfile : "stdout");
		fprintf(p->out,"%9.9s: %s\n","separator", p->separator);
		fprintf(p->out,"%9.9s: ","width");
		for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
			fprintf(p->out,"%d ",p->colWidth[i]);
		}
		fprintf(p->out,"\n\n");
	}else if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
		char **azResult;
		int nRow, rc;
		char *zErrMsg;
		open_db(p);
		if( nArg==1 ){
			rc=sqlite_get_table(p->db,
						"SELECT name FROM sqlite_master "
						"WHERE type IN ('table','view') "
						"UNION ALL "
						"SELECT name FROM sqlite_temp_master "
						"WHERE type IN ('table','view') "
						"ORDER BY 1",
						&azResult, &nRow, 0, &zErrMsg
				);
		}else{
			rc=sqlite_get_table_printf(p->db,
							"SELECT name FROM sqlite_master "
							"WHERE type IN ('table','view') AND name LIKE '%%%q%%' "
							"UNION ALL "
							"SELECT name FROM sqlite_temp_master "
							"WHERE type IN ('table','view') AND name LIKE '%%%q%%' "
							"ORDER BY 1",
							&azResult, &nRow, 0, &zErrMsg, azArg[1], azArg[1]
				);
		}
		if( zErrMsg ){
			fprintf(stderr,"Error: %s\n", zErrMsg);
			sqlite_freemem(zErrMsg);
		}
		if( rc==SQLITE_OK ){
			int len, maxlen=0;
			int i, j;
			int nPrintCol, nPrintRow;
			for(i=1; i<=nRow; i++){
				if( azResult[i]==0 ) continue;
				len=strlen(azResult[i]);
				if( len>maxlen ) maxlen=len;
			}
			nPrintCol=80/(maxlen+2);
			if( nPrintCol<1 ) nPrintCol=1;
			nPrintRow=(nRow + nPrintCol - 1)/nPrintCol;
			for(i=0; i<nPrintRow; i++){
				for(j=i+1; j<=nRow; j+=nPrintRow){
					char *zSp=j<=nPrintRow ? "" : "  ";
					printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
				}
				printf("\n");
			}
    		}
		sqlite_free_table(azResult);
	} else if( c=='t' && n>1 && strncmp(azArg[0], "timeout", n)==0 && nArg>=2 ){
		open_db(p);
		sqlite_busy_timeout(p->db, atoi(azArg[1]));
	} else if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
		int j;
		for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
			p->colWidth[j-1]=atoi(azArg[j]);
		}
	} else {
		fprintf(stderr, "unknown command or invalid arguments: \"%s\". Enter \".help\" for help\n", azArg[0]);
	}
	return rc;
}
Пример #26
0
/* Main entry point for batch, accepts an array of arguments and a
 * pointer to the cliuser_t structure */
int cmd_batch(char **argv, cliuser_t *usr)
{
	unsigned int argc;
	bool continue_despite_errors = false;

	/* Count the arguments */
	for (argc = 0; argv[argc] != NULL; argc ++);

	if (argc < 2) {
		printf("%s - no input file provided.\n", cmdname);
		return CMD_FAILURE;
	}

	if (argc > 2) {
		if (str_cmp(argv[2], "-c") == 0)
			continue_despite_errors = true;
	}

	int rc = 0;
	FILE *batch = fopen(argv[1], "r");
	if (batch == NULL) {
		printf("%s - Cannot open file %s\n", cmdname, argv[1]);
		return CMD_FAILURE;
	} else {
		cliuser_t fusr;
		fusr.name = usr->name;
		fusr.cwd = usr->cwd;
		fusr.prompt = usr->prompt;
		fusr.line = malloc(INPUT_MAX + 1);
		char *cur = fusr.line;
		char *end = fusr.line + INPUT_MAX;
		int c = fgetc(batch);
		while (fusr.line != NULL) {
			if (c == '\n' || c == EOF || cur == end) {
				*cur = '\0';
				if (cur == fusr.line) {
					/* skip empty line */
					rc = 0;
					free(cur);
				} else {
					printf(">%s\n", fusr.line);
					rc = process_input(&fusr);
					/* fusr->line was freed by process_input() */
					if ((rc != EOK) && continue_despite_errors) {
						/* Mute the error. */
						rc = EOK;
					}
				}
				if (rc == 0 && c != EOF) {
					fusr.line = malloc(INPUT_MAX + 1);
					cur = fusr.line;
					end = fusr.line + INPUT_MAX;
				} else {
					break;
				}
			} else {
				*cur++ = c;
			}
			c = fgetc(batch);
		}
		fclose(batch);
	}

	return CMD_SUCCESS;
}
Пример #27
0
/*
 * Performs the interactive session.  This handles data transmission between
 * the client and the program.  Note that the notion of stdin, stdout, and
 * stderr in this function is sort of reversed: this function writes to
 * stdin (of the child program), and reads from stdout and stderr (of the
 * child program).
 */
void
server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
{
	fd_set *readset = NULL, *writeset = NULL;
	int max_fd = 0;
	u_int nalloc = 0;
	int wait_status;	/* Status returned by wait(). */
	pid_t wait_pid;		/* pid returned by wait(). */
	int waiting_termination = 0;	/* Have displayed waiting close message. */
	u_int64_t max_time_milliseconds;
	u_int previous_stdout_buffer_bytes;
	u_int stdout_buffer_bytes;
	int type;

	debug("Entering interactive session.");

	/* Initialize the SIGCHLD kludge. */
	child_terminated = 0;
	mysignal(SIGCHLD, sigchld_handler);

	if (!use_privsep) {
		signal(SIGTERM, sigterm_handler);
		signal(SIGINT, sigterm_handler);
		signal(SIGQUIT, sigterm_handler);
	}

	/* Initialize our global variables. */
	fdin = fdin_arg;
	fdout = fdout_arg;
	fderr = fderr_arg;

	/* nonblocking IO */
	set_nonblock(fdin);
	set_nonblock(fdout);
	/* we don't have stderr for interactive terminal sessions, see below */
	if (fderr != -1)
		set_nonblock(fderr);

	if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
		fdin_is_tty = 1;

	connection_in = packet_get_connection_in();
	connection_out = packet_get_connection_out();

	notify_setup();

	previous_stdout_buffer_bytes = 0;

	/* Set approximate I/O buffer size. */
	if (packet_is_interactive())
		buffer_high = 4096;
	else
		buffer_high = 64 * 1024;

#if 0
	/* Initialize max_fd to the maximum of the known file descriptors. */
	max_fd = MAX(connection_in, connection_out);
	max_fd = MAX(max_fd, fdin);
	max_fd = MAX(max_fd, fdout);
	if (fderr != -1)
		max_fd = MAX(max_fd, fderr);
#endif

	/* Initialize Initialize buffers. */
	buffer_init(&stdin_buffer);
	buffer_init(&stdout_buffer);
	buffer_init(&stderr_buffer);

	/*
	 * If we have no separate fderr (which is the case when we have a pty
	 * - there we cannot make difference between data sent to stdout and
	 * stderr), indicate that we have seen an EOF from stderr.  This way
	 * we don't need to check the descriptor everywhere.
	 */
	if (fderr == -1)
		fderr_eof = 1;

	server_init_dispatch();

	/* Main loop of the server for the interactive session mode. */
	for (;;) {

		/* Process buffered packets from the client. */
		process_buffered_input_packets();

		/*
		 * If we have received eof, and there is no more pending
		 * input data, cause a real eof by closing fdin.
		 */
		if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
			if (fdin != fdout)
				close(fdin);
			else
				shutdown(fdin, SHUT_WR); /* We will no longer send. */
			fdin = -1;
		}
		/* Make packets from buffered stderr data to send to the client. */
		make_packets_from_stderr_data();

		/*
		 * Make packets from buffered stdout data to send to the
		 * client. If there is very little to send, this arranges to
		 * not send them now, but to wait a short while to see if we
		 * are getting more data. This is necessary, as some systems
		 * wake up readers from a pty after each separate character.
		 */
		max_time_milliseconds = 0;
		stdout_buffer_bytes = buffer_len(&stdout_buffer);
		if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
		    stdout_buffer_bytes != previous_stdout_buffer_bytes) {
			/* try again after a while */
			max_time_milliseconds = 10;
		} else {
			/* Send it now. */
			make_packets_from_stdout_data();
		}
		previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);

		/* Send channel data to the client. */
		if (packet_not_very_much_data_to_write())
			channel_output_poll();

		/*
		 * Bail out of the loop if the program has closed its output
		 * descriptors, and we have no more data to send to the
		 * client, and there is no pending buffered data.
		 */
		if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
		    buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
			if (!channel_still_open())
				break;
			if (!waiting_termination) {
				const char *s = "Waiting for forwarded connections to terminate...\r\n";
				char *cp;
				waiting_termination = 1;
				buffer_append(&stderr_buffer, s, strlen(s));

				/* Display list of open channels. */
				cp = channel_open_message();
				buffer_append(&stderr_buffer, cp, strlen(cp));
				free(cp);
			}
		}
		max_fd = MAX(connection_in, connection_out);
		max_fd = MAX(max_fd, fdin);
		max_fd = MAX(max_fd, fdout);
		max_fd = MAX(max_fd, fderr);
		max_fd = MAX(max_fd, notify_pipe[0]);

		/* Sleep in select() until we can do something. */
		wait_until_can_do_something(&readset, &writeset, &max_fd,
		    &nalloc, max_time_milliseconds);

		if (received_sigterm) {
			logit("Exiting on signal %d", (int)received_sigterm);
			/* Clean up sessions, utmp, etc. */
			cleanup_exit(255);
		}

		/* Process any channel events. */
		channel_after_select(readset, writeset);

		/* Process input from the client and from program stdout/stderr. */
		process_input(readset);

		/* Process output to the client and to program stdin. */
		process_output(writeset);
	}
	free(readset);
	free(writeset);

	/* Cleanup and termination code. */

	/* Wait until all output has been sent to the client. */
	drain_output();

	debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
	    stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);

	/* Free and clear the buffers. */
	buffer_free(&stdin_buffer);
	buffer_free(&stdout_buffer);
	buffer_free(&stderr_buffer);

	/* Close the file descriptors. */
	if (fdout != -1)
		close(fdout);
	fdout = -1;
	fdout_eof = 1;
	if (fderr != -1)
		close(fderr);
	fderr = -1;
	fderr_eof = 1;
	if (fdin != -1)
		close(fdin);
	fdin = -1;

	channel_free_all();

	/* We no longer want our SIGCHLD handler to be called. */
	mysignal(SIGCHLD, SIG_DFL);

	while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
		if (errno != EINTR)
			packet_disconnect("wait: %.100s", strerror(errno));
	if (wait_pid != pid)
		error("Strange, wait returned pid %ld, expected %ld",
		    (long)wait_pid, (long)pid);

	/* Check if it exited normally. */
	if (WIFEXITED(wait_status)) {
		/* Yes, normal exit.  Get exit status and send it to the client. */
		debug("Command exited with status %d.", WEXITSTATUS(wait_status));
		packet_start(SSH_SMSG_EXITSTATUS);
		packet_put_int(WEXITSTATUS(wait_status));
		packet_send();
		packet_write_wait();

		/*
		 * Wait for exit confirmation.  Note that there might be
		 * other packets coming before it; however, the program has
		 * already died so we just ignore them.  The client is
		 * supposed to respond with the confirmation when it receives
		 * the exit status.
		 */
		do {
			type = packet_read();
		}
		while (type != SSH_CMSG_EXIT_CONFIRMATION);

		debug("Received exit confirmation.");
		return;
	}
	/* Check if the program terminated due to a signal. */
	if (WIFSIGNALED(wait_status))
		packet_disconnect("Command terminated on signal %d.",
				  WTERMSIG(wait_status));

	/* Some weird exit cause.  Just exit. */
	packet_disconnect("wait returned status %04x.", wait_status);
	/* NOTREACHED */
}
Пример #28
0
int main(int argc, char **argv){
  char *zErrMsg = 0;
  struct callback_data data;
  int origArgc = argc;
  char **origArgv = argv;
  int i;
  extern int sqliteOsFileExists(const char*);

#ifdef __MACOS__
  argc = ccommand(&argv);
  origArgc = argc;
  origArgv = argv;
#endif

  Argv0 = argv[0];
  main_init(&data);

  /* Make sure we have a valid signal handler early, before anything
  ** else is done.
  */
#ifdef SIGINT
  signal(SIGINT, interrupt_handler);
#endif

  /* Locate the name of the database file
  */
  for(i=1; i<argc; i++){
    if( argv[i][0]!='-' ) break;
    if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
      i++;
    }
  }
  data.zDbFilename = i<argc ? argv[i] : ":memory:";
  data.out = stdout;

  /* Go ahead and open the database file if it already exists.  If the
  ** file does not exist, delay opening it.  This prevents empty database
  ** files from being created if a user mistypes the database name argument
  ** to the sqlite command-line tool.
  */
  if( sqliteOsFileExists(data.zDbFilename) ){
    open_db(&data);
  }

  /* Process the ~/.sqliterc file, if there is one
  */
  process_sqliterc(&data,NULL);

  /* Process command-line options
  */
  while( argc>=2 && argv[1][0]=='-' ){
    if( argc>=3 && strcmp(argv[1],"-init")==0 ){
      /* If we get a -init to do, we have to pretend that
      ** it replaced the .sqliterc file. Soooo, in order to
      ** do that we need to start from scratch...*/
      main_init(&data);

      /* treat this file as the sqliterc... */
      process_sqliterc(&data,argv[2]);

      /* fix up the command line so we do not re-read
      ** the option next time around... */
      {
        int i = 1;
        for(i=1;i<=argc-2;i++) {
          argv[i] = argv[i+2];
        }
      }
      origArgc-=2;

      /* and reset the command line options to be re-read.*/
      argv = origArgv;
      argc = origArgc;

    }else if( strcmp(argv[1],"-html")==0 ){
      data.mode = MODE_Html;
      argc--;
      argv++;
    }else if( strcmp(argv[1],"-list")==0 ){
      data.mode = MODE_List;
      argc--;
      argv++;
    }else if( strcmp(argv[1],"-line")==0 ){
      data.mode = MODE_Line;
      argc--;
      argv++;
    }else if( strcmp(argv[1],"-column")==0 ){
      data.mode = MODE_Column;
      argc--;
      argv++;
    }else if( argc>=3 && strcmp(argv[1],"-separator")==0 ){
      sprintf(data.separator,"%.*s",(int)sizeof(data.separator)-1,argv[2]);
      argc -= 2;
      argv += 2;
    }else if( argc>=3 && strcmp(argv[1],"-nullvalue")==0 ){
      sprintf(data.nullvalue,"%.*s",(int)sizeof(data.nullvalue)-1,argv[2]);
      argc -= 2;
      argv += 2;
    }else if( strcmp(argv[1],"-header")==0 ){
      data.showHeader = 1;
      argc--;
      argv++;
    }else if( strcmp(argv[1],"-noheader")==0 ){
      data.showHeader = 0;
      argc--;
      argv++;
    }else if( strcmp(argv[1],"-echo")==0 ){
      data.echoOn = 1;
      argc--;
      argv++;
    }else if( strcmp(argv[1],"-version")==0 ){
      printf("%s\n", sqlite_version);
      return 1;
    }else if( strcmp(argv[1],"-help")==0 ){
      usage(1);
    }else{
      fprintf(stderr,"%s: unknown option: %s\n", Argv0, argv[1]);
      fprintf(stderr,"Use -help for a list of options.\n");
      return 1;
    }
  }

  if( argc<2 ){
    usage(0);
  }else if( argc==3 ){
    /* Run just the command that follows the database name
    */
    if( argv[2][0]=='.' ){
      do_meta_command(argv[2], &data);
      exit(0);
    }else{
      int rc;
      open_db(&data);
      rc = sqlite_exec(db, argv[2], callback, &data, &zErrMsg);
      if( rc!=0 && zErrMsg!=0 ){
        fprintf(stderr,"SQL error: %s\n", zErrMsg);
        exit(1);
      }
    }
  }else{
    /* Run commands received from standard input
    */
    if( isatty(fileno(stdout)) && isatty(fileno(stdin)) ){
      char *zHome;
      char *zHistory = 0;
      printf(
        "SQLite version %s\n"
        "Enter \".help\" for instructions\n",
        sqlite_version
      );
      zHome = find_home_dir();
      if( zHome && (zHistory = malloc(strlen(zHome)+20))!=0 ){
        sprintf(zHistory,"%s/.sqlite_history", zHome);
      }
      if( zHistory ) read_history(zHistory);
      process_input(&data, 0);
      if( zHistory ){
        stifle_history(100);
        write_history(zHistory);
      }
    }else{
      process_input(&data, stdin);
    }
  }
  set_table_name(&data, 0);
  if( db ) sqlite_close(db);
  return 0;
}
Пример #29
0
int dispatch_actions(void)
{
   int fd,n,ret,timeout,elapsed_ms;
   static int ktimeout;
   struct pollfd fds[1];
   struct timeval last,now;

   /* now the process_no is set, I delete the pt (process_table) global var,
	* because it confuses LM_*() */
   pt=0;
   fd=my_as->u.as.action_fd;
   fds[0].fd=fd;
   fds[0].events=POLLIN|POLLHUP;
   fds[0].revents=0;
   my_parent=getppid();
   snprintf(whoami,MAX_WHOAMI_LEN,"[%.*s] Action dispatcher",my_as->name.len,my_as->name.s);
   if(jain_ping_timeout && servlet_ping_timeout)
      ktimeout=jain_ping_timeout<servlet_ping_timeout?jain_ping_timeout:servlet_ping_timeout;
   else if(jain_ping_timeout)
      ktimeout=jain_ping_timeout;
   else if(servlet_ping_timeout)
      ktimeout=servlet_ping_timeout;
   /*ac_buffer is pkg_malloc because only this process (action dispatcher) will use it*/
   if((my_as->u.as.ac_buffer.s = pkg_malloc(AS_BUF_SIZE))==0){
      LM_ERR("no more pkg mem\n");
      return -1;
   }
   my_as->u.as.ac_buffer.len=0;
   if(use_ha){
      timeout=ktimeout;
      while(1){
	 gettimeofday(&last,NULL);
	 print_pingtable(&my_as->u.as.jain_pings,-1,1);
	 if(0>(n=poll(fds,1,timeout))){
	    if(errno==EINTR){
	       gettimeofday(&last,NULL);
	       continue;
	    }else if(errno==EBADF){
	       LM_ERR("EBADF !!\n");
	    }else{
	       LM_ERR("on poll\n");
	    }
	 }else if(n==0){/*timeout*/
	    if (0>(ret=process_pings(&my_as->u.as.jain_pings))) {
	       return ret;
	    }
	    timeout=ktimeout;
	 }else{ /*events*/
	    if (0>(ret=process_input(fd))) {
	       return ret;
	    }
	    gettimeofday(&now,NULL);
	    elapsed_ms=((now.tv_sec-last.tv_sec)*1000)+((now.tv_usec-last.tv_usec)/1000);
	    if(elapsed_ms<timeout){
	       timeout-=elapsed_ms;
	    }else{
	       if(0>(ret=process_pings(&my_as->u.as.jain_pings))){
		  return ret;
	       }
	       timeout=ktimeout;
	    }
	 }
	 fds[0].events=POLLIN|POLLHUP;
	 fds[0].revents=0;
      }
   }else{
      do{
	 ret=process_input(fd);
      }while(ret>=0);
   }

   return 0;
}
Пример #30
0
void zmq::pgm_receiver_t::in_event ()
{
    // Read data from the underlying pgm_socket.
    const pgm_tsi_t *tsi = NULL;

    if (has_rx_timer) {
        cancel_timer (rx_timer_id);
        has_rx_timer = false;
    }

    //  TODO: This loop can effectively block other engines in the same I/O
    //  thread in the case of high load.
    while (true) {

        //  Get new batch of data.
        //  Note the workaround made not to break strict-aliasing rules.
        void *tmp = NULL;
        ssize_t received = pgm_socket.receive (&tmp, &tsi);
        inpos = (unsigned char*) tmp;

        //  No data to process. This may happen if the packet received is
        //  neither ODATA nor ODATA.
        if (received == 0) {
            if (errno == ENOMEM || errno == EBUSY) {
                const long timeout = pgm_socket.get_rx_timeout ();
                add_timer (timeout, rx_timer_id);
                has_rx_timer = true;
            }
            break;
        }

        //  Find the peer based on its TSI.
        peers_t::iterator it = peers.find (*tsi);

        //  Data loss. Delete decoder and mark the peer as disjoint.
        if (received == -1) {
            if (it != peers.end ()) {
                it->second.joined = false;
                if (it->second.decoder != NULL) {
                    delete it->second.decoder;
                    it->second.decoder = NULL;
                }
            }
            break;
        }

        //  New peer. Add it to the list of know but unjoint peers.
        if (it == peers.end ()) {
            peer_info_t peer_info = {false, NULL};
            it = peers.insert (peers_t::value_type (*tsi, peer_info)).first;
        }

        insize = static_cast <size_t> (received);

        //  Read the offset of the fist message in the current packet.
        zmq_assert (insize >= sizeof (uint16_t));
        uint16_t offset = get_uint16 (inpos);
        inpos += sizeof (uint16_t);
        insize -= sizeof (uint16_t);

        //  Join the stream if needed.
        if (!it->second.joined) {

            //  There is no beginning of the message in current packet.
            //  Ignore the data.
            if (offset == 0xffff)
                continue;

            zmq_assert (offset <= insize);
            zmq_assert (it->second.decoder == NULL);

            //  We have to move data to the begining of the first message.
            inpos += offset;
            insize -= offset;

            //  Mark the stream as joined.
            it->second.joined = true;

            //  Create and connect decoder for the peer.
            it->second.decoder = new (std::nothrow)
                v1_decoder_t (0, options.maxmsgsize);
            alloc_assert (it->second.decoder);
        }

        int rc = process_input (it->second.decoder);
        if (rc == -1) {
            if (errno == EAGAIN) {
                active_tsi = tsi;

                //  Stop polling.
                reset_pollin (pipe_handle);
                reset_pollin (socket_handle);

                break;
            }

            it->second.joined = false;
            delete it->second.decoder;
            it->second.decoder = NULL;
            insize = 0;
        }
    }

    //  Flush any messages decoder may have produced.
    session->flush ();
}