Ejemplo n.º 1
0
int main(void)
{
	int n;
	n=print_args(-1,"hello","world",NULL);
	printf("first,without NULL: %d\n",n);
	n=print_args(-1,"China","beijing","Olympic",NULL);
	printf("second with NULL; %d\n",n);
	return 0;
}
Ejemplo n.º 2
0
int main(int argc, char *argv[]) {
   struct arguments args;

   /* Process arguments */
   init_args(&args);
   if (parse_args(argc, argv, &args) < 0) return -1;
   validate_args(&args);
   if (args.verbose) print_args(&args);

   switch (args.mode) {
      case CLI_MODE:
         tun_cli(&args);
         break;
      case SERV_MODE:
         tun_serv(&args);
         break;
      case FULLMESH_MODE:
         tun_peer(&args);
         break;
      default:
         break;
   }

   return 0;
}
Ejemplo n.º 3
0
int subcommand1(int start, int argc, char **argv)
{
    int ret = 0;
    cargo_t mod1;
    if (!argv) return -1;
    if (cargo_init(&mod1, 0, "%s command1", argv[0]))
    {
        fprintf(stderr, "Failed to init command line parsing\n");
        return -1;
    }

    ret |= add_global_opts(mod1);
    ret |= add_module1_opts(mod1);
    assert(ret == 0);

    print_args(argc - start, &argv[start]);

    if (cargo_parse(mod1, 0, start, argc, argv)) return -1;

    printf("opt1 == %s\n", global_1);

    cargo_destroy(&mod1);

    return ret;
}
Ejemplo n.º 4
0
Archivo: main.c Proyecto: gpalma/semep
int main(int argc, char **argv)
{
     int len;
     clock_t ti, tf;
     static char *name;
     struct input_data in;
     double density;

     ti = clock();
     parse_args(argc, argv);
     print_args();
     len = strlen(g_args.graph_filename) + 1;
     name = xcalloc(len, 1);
     get_name(g_args.graph_filename, len, name);
     printf("\n**** Go semEP! **** \n");
     in = get_input_data(g_args.matrix_left_filename, g_args.matrix_right_filename,
			 g_args.left_filename, g_args.right_filename,
			 g_args.graph_filename);
     density = semEP_solver(&in.left_matrix, &in.right_matrix, &in.left_terms, &in.right_terms,
			    &in.td, &in.bpgraph, g_args.threshold_left, g_args.threshold_right, name);
     printf("Average density of the partitions: %.4f \n", density);
     printf("*** semEP finished ***\n");
     tf = clock();
     printf("\nTotal time %.3f secs\n", (double)(tf-ti)/CLOCKS_PER_SEC);
     free(name);
     free_input_data(&in);

     return 0;
}
Ejemplo n.º 5
0
Archivo: main.c Proyecto: gpalma/taxsim
int main(int argc, char **argv)
{
     clock_t ti, tf;
     struct input_data in;

     ti = clock();     
     parse_args(argc, argv);
     print_args();

     /* start solver */
     printf("\n**** Solver Begins ****\n");
     in = get_input_ontology_data(g_args.graph_filename,
				  g_args.desc_filename,
				  g_args.annt_filename, 
				  g_args.description);
     taxonomic_similarity(&in.g, &in.anntt,
			  g_args.n_threads,
			  in.descriptions,
			  g_args.d, g_args.lca);
     tf = clock();
     free_input_data(&in);
     printf("\nTotal Time %.3f secs\n", (double)(tf-ti)/CLOCKS_PER_SEC);
     
     return 0;
}
/* non-main function call */
void print_fncall(Stmt stmt, char* procName) {
    printf("# fncall\n");
    if(stmt->info.fncall.args)
        print_args(stmt->info.fncall.args,0,procName,0,stmt->info.fncall.id);
    printf("call proc_%s\n", stmt->info.fncall.id);

}
Ejemplo n.º 7
0
void			ft_ls(int ac, char **av, int i, t_info *info)
{
	t_dlst		headdir;
	t_dlst		headerror;

	dlst_init(&headdir);
	dlst_init(&headerror);
	dlst_init(&info->headfile);
	reset_max_info(info);
	if (ac - 1 > 1)
		SET(info->opt, OPT_MD);
	while (i < ac)
	{
		ls_fetch_in_arg(av[i], &info->headfile, &headdir, &headerror);
		i++;
	}
	if (!dlst_empty(&headerror))
	{
		flush_headerror(&headerror);
		info->flush = 1;
	}
	if (!dlst_empty(&info->headfile))
	{
		sort_merge_lst(&info->headfile, info);
		print_args(info, &headdir);
	}
	launch_dir_lst(&headdir, info);
}
Ejemplo n.º 8
0
int					ft_select(t_param **debut)
{
	char	buf[10];
	int		ret;

	ft_tputs("vi", 1);
	if (print_args(*debut) == -1)
		return (-1);
	if (print_args(*debut) == -2)
	{
		ft_tputs("cl", 1);
		ft_dprintf(STDERR_FILENO, "\x1b[31;01mSCREEN SIZE TOO SMALL\x1b[0;m");
	}
	ret = read(0, buf, 10);
	ft_bzero(&buf[ret], 10 - ret);
	return (read_key(buf, debut));
}
Ejemplo n.º 9
0
void PrintCommand(Command *command)
{
	int i;
	for(i=0; i<command->num_sub_commands; i++)
	{
		printf("Sub command #%d\n", i);
		print_args(command->sub_commands[i].argv);
	}
}
Ejemplo n.º 10
0
int main(int argc, char * argv[])
{
  
  long_index = 0;
  init_args();
  parse_long(argc, argv);
  printf("Correlation method is %d\n",argum.correlation_method);
  print_args();
  return 0;
}
Ejemplo n.º 11
0
int main( int argc, char *argv[] )
{
	print_args(argc,argv);
	
	bool stop=false;
	init_claws();
	
	time_t t;
	time(&t);
	time_stamp = *(localtime(&t));
	printf("====================== CLAW =========================\n");

	if (argc>1) {

		if (strcmp(argv[1], "stop")==0) {
			stop = true;
			printf("Stop!");
			int count = 10;
			while (count--) {
				mot.ForwardM1 (address, 0);
				mot.ForwardM2 (address, 0);		
				mot2.ForwardM1(address, 0);
				mot2.ForwardM2(address, 0);	
		/*		mot3.ForwardM1(address, 0);
				mot3.ForwardM2(address, 0);
				mot4.ForwardM1(address, 0);
				mot4.ForwardM2(address, 0); */
				usleep(1000000);	// 0.1 sec
				usleep(1000000);	// 0.1 sec
			}
			exit(1);
		}
	}
	 
	while (1)
	{				
		printf("\nForward:\n");
		mot.ForwardM1(address, 64);
		mot.ForwardM2(address, 64);
/*		mot2.ForwardM1(address, 64);
		mot2.ForwardM2(address, 64);		*/
		usleep(1000000);	// 0.1 sec
		//usleep(1000000);	// 0.1 sec
		//read_main_battery();
		
		printf("\nBackward:\n");		
		mot.BackwardM1(address, 64);
		mot.BackwardM2(address, 64);
/*		mot2.BackwardM1(address, 64);
		mot2.BackwardM2(address, 64); */
		usleep(1000000);	// 0.1 sec		
		//usleep(1000000);	// 0.1 sec
	}
}
void print_args(Exprs exprs,int reg, char* procName, 
    int paramNum,char* callee) {
    
    Expr first = exprs->first;
    Exprs rest = exprs->rest;
    if (first) {
            print_arg(first,reg,procName,paramNum,callee);
        if (rest) {
            print_args(rest,reg+1,procName,paramNum+1,callee);  
        }
    }
}
Ejemplo n.º 13
0
int
main(int argc,char **argv)
{
    print_version(argv[0]);
    print_args(argc,argv);
    process_args(argc,argv);
    OpenAllFiles();
    GenerateInitialFileLines();
    ParseDefinitionsAndWriteOutput();
    WriteFileTrailers();
    CloseAllFiles();
    return 0;
}
Ejemplo n.º 14
0
int main()
{
	 char s[200];
	 char *argv[10];
	 int argc;

	 // Read a string from the user
	 printf("Enter a string: ");
	 fgets(s, sizeof s, stdin);
	 // Extract arguments and print them
	 get_args(s, argv, 10);
	 print_args(argv);
}
Ejemplo n.º 15
0
void log_proxy_call(struct filesys_obj *obj1, region_t r, struct cap_args args,
		    struct cap_args *result)
{
  struct log_proxy *obj = (void *) obj1;
  
  fprintf(stderr, "args:\n");
  print_args(args);

  cap_call(obj->x, r, args, result);

  fprintf(stderr, "result:\n");
  print_args(*result);
  fprintf(stderr, "\n");

  {
    cap_t *caps = region_alloc(r, result->caps.size * sizeof(cap_t));
    int i;
    for(i = 0; i < result->caps.size; i++) {
      caps[i] = make_log_proxy(result->caps.caps[i]);
    }
    result->caps = cap_seq_make(caps, result->caps.size);
  }
}
Ejemplo n.º 16
0
gboolean
mu_util_printerr_encoded (const char *frm, ...)
{
	va_list args;
	gboolean rv;

	g_return_val_if_fail (frm, FALSE);

	va_start (args, frm);
	rv = print_args (stderr, frm, args);
	va_end (args);

	return rv;
}
Ejemplo n.º 17
0
static void usage(FILE *fp, char *prog, int argc, char *argv[])
{
	fprintf(fp, "Usage: %s [OPTION]... [FILE]...\n"
		"Compress or uncompress FILEs (by default, compress FILES in-place).\n"
		"\n"
		"Mandatory arguments to long options are mandatory for short options too.\n"
		"\n"
		"  -c, --stdout      write on standard output, keep original files unchanged\n"
		"  -d, --decompress  decompress\n"
		"  -f, --force       force overwrite of output file and compress links\n"
		"  -h, --help        give this help\n"
		"  -l, --list        list compressed file contents\n"
		"  -L, --license     display software license\n"
		"  -N, --name        save or restore the original name and time stamp\n"
		"  -q, --quiet       suppress all warnings\n"
		"  -S, --suffix=SUF  use suffix SUF on compressed files\n"
		"  -v, --verbose     verbose mode\n"
		"  -V, --version     display version number\n"
		"  -1, --fast        compress faster\n"
		"  -9, --best        compress better\n"
		"\n"
		"Special options for testing and debugging:\n"
		"  -A, --accelerator-type=GENWQE|CAPI CAPI is only available for System p\n"
		"  -B, --card=<card_no> -1 is for automatic card selection\n"
		"  -X, --cpu <cpu>   force to run on CPU <cpu>\n"
		"  -s, --software    force to use software compression/decompression\n"
		"  -i, --i_bufsize   input buffer size (%d KiB)\n"
		"  -o, --o_bufsize   output buffer size (%d KiB)\n"
		"  -N, --name=NAME   write NAME into gzip header\n"
		"  -C, --commente=CM write CM into gzip header\n"
		"  -E, --extra=EXTRA write EXTRA (file) into gzip header\n"
		"\n"
		"With no FILE, or when FILE is -, read standard input.\n"
		"\n"
		"NOTE: Not all options are supported in this limited version!\n"
		"Suggestions or patches are welcome!\n"
		"\n"
		"Report bugs via https://github.com/ibm-genwqe/genwqe-user.\n"
		"\n", prog, CHUNK_i/1024, CHUNK_o/1024);

	print_args(fp, argc, argv);
}
Ejemplo n.º 18
0
static int		get_syscall(int pid, char **strtab)
{
  static char		first_call = 1;
  struct user		infos;
  struct syscalls	*call;
  long			word;
  int			status;

  /* Return call informations */
  if (ptrace(PTRACE_GETREGS, pid, NULL, &infos) == -1)
    {      fprintf(stderr, "getregs fail\n");      return 1;    }
  word = ptrace(PTRACE_PEEKTEXT, pid, infos.regs.rip, NULL);
  if ((word & 0xFFFF) != 0x050F)
    return 0;
  if (!(call = get_call_infos(strtab[(int)infos.regs.rax])))
    {
      fprintf(stderr, "Unimplemented syscall : %s\n",
	      strtab[(int)infos.regs.rax]);
      return 0;
    }
  if (first_call && !(first_call = 0))
    return 0; // first call is our strace() call
  fprintf(stderr, "%s(", call->name);
  print_args(call->name, call->p, infos, pid);
  fprintf(stderr, ")");
  fflush(stderr);
  /* Go to return value */
  ptrace(PTRACE_SINGLESTEP, pid, NULL, 0);
  wait4(pid, &status, WUNTRACED, NULL);
  if (ptrace(PTRACE_GETREGS, pid, NULL, &infos) == -1)
    {      fprintf(stderr, "\t= ?\n");      return 1;    }
  if (strchr(call->rtype, '*')) {
    fprintf(stderr, "\t= %#lx", infos.regs.rax);
  } else {
    if ((int)infos.regs.rax < 0)
      fprintf(stderr, "\t= %d (%s)", -1, strerror(-infos.regs.rax));
    else
      fprintf(stderr, "\t= %ld", infos.regs.rax);
  }
  fprintf(stderr, "\n");
  return 0;
}
Ejemplo n.º 19
0
void printit_anything(printit *x, t_symbol *s, short argc, t_atom *argv) {
	post("%s: received MESSAGE \"%s\" (%p, s_thing %p) with %d argument(s):", 
	     x->my_name->s_name, s->s_name, s, s->s_thing, argc);

	print_args(x, argc, argv);
	
	if (s == ps_FullPacket && argc == 2 && argv[0].a_type == A_LONG && argv[1].a_type == A_LONG) {
	  int size = argv[0].a_w.w_long;
	  char *bufptr = (char *) argv[1].a_w.w_long;
	  object_post((t_object *)x, "It looks like an OSC packet");
	  if (size < x->min_OSCPacket_size) {
	    post("but the size is only %ld bytes, so I won't try to print it.",
		 size);
	  } else if (size > x->max_OSCPacket_size) {
	    post("but the size (%ld) looks too big, so I won't try to print it",
		 size);
	  } else {
		PrintOSCPacket(bufptr, size);
	  }
	}
}
Ejemplo n.º 20
0
int main(int argc,char * argv[]){

	while(1){
		printf("mysh%% ");

		init();

		getinputs();

		printf("Show the command:\n");
		printf("command:%s",token);

		while( (token = strtok_r(NULL," ",&save_ptr)) != NULL){
		
			if(*token == '<'){
				iof[0] = SET;			
				if( isgraph(*(token + 1))){
					ios[0] = token + 1;
					state = NORMAL; 
				} else {
					state = INPUT;
				}

			} else if(*token == '>'){
				iof[1] = SET;
				if( isgraph(*(token + 1))){
					ios[1] = token + 1;
					state = NORMAL;
				}else{
					state = OUTPUT;
				}
			} else {
				switch(state){
				case NORMAL:
					if((found = strchr(token,'<'))){
						*found = '\0';
						args[args_i++] = token;
						iof[0] = SET;
						if( isgraph(*(found+1))) {
							ios[0] = found + 1;
							state = NORMAL;
						}else{
							state = INPUT;
						}
					}else if((found = strchr(token,'>'))){
						*found = '\0';
						args[args_i++] = token;
						iof[1] = SET;
						if( isgraph(*(found+1))) {
							ios[1] = found + 1;
							state = NORMAL;
						}else{
							state = OUTPUT;
						}
					
					}else{
						args[args_i++] = token;
					}

					break;
				case INPUT:
					if(! isspace(*token) ){
						ios[0] = token;
						state = NORMAL;
					}
					break;
				case OUTPUT:
					if(! isspace(*token) ){
						ios[1] = token;
						state = NORMAL;
					}
					break;
				default:
					break;	
			    }
			}

		}
        
		print_args();
	}
	return 0;	
}
Ejemplo n.º 21
0
int32_t parse_arguments( struct programmer_arguments *args,
                         const size_t argc,
                         char **argv )
{
    int32_t i;
    int32_t status = 0;

    if( NULL == args )
        return -1;

    /* initialize the argument block to empty, known values */
    args->target  = tar_none;
    args->command = com_none;
    args->quiet   = 0;
    args->suppressbootloader = 0;

    /* Special case - check for the help commands which do not require a device type */
    if( argc == 2 ) {
        if( 0 == strcasecmp(argv[1], "--version") ) {
            fprintf( stderr, PACKAGE_STRING "\n");
            return 1;
        }
        if( 0 == strcasecmp(argv[1], "--targets") ) {
            list_targets( LIST_STD );
            return 1;
        }
        if( 0 == strcasecmp(argv[1], "--targets-tex") ) {
            list_targets( LIST_TEX );
            return 1;
        }
        if( 0 == strcasecmp(argv[1], "--targets-html") ) {
            list_targets( LIST_HTML );
            return 1;
        }
        if( 0 == strcasecmp(argv[1], "--help") ||
                0 == strcasecmp(argv[1], "-h") ||
                0 == strcasecmp(argv[1], "--h") ) {
            usage();
            return 1;
        }
    }

    /* Make sure there are the minimum arguments */
    if( argc < 3 ) {
        basic_help();
        return -1;
    }

    if( 0 != assign_target(args, argv[1], target_map) ) {
        fprintf( stderr, "Unsupported target '%s'.\n", argv[1]);
        status = -3;
        goto done;
    }

    if( 0 != assign_option((int32_t *) &(args->command), argv[2], command_map) ) {
        status = -4;
        goto done;
    }

    /* These were taken care of above. */
    *argv[0] = '\0';
    *argv[1] = '\0';
    *argv[2] = '\0';

    /* assign command specific default values */
    switch( args->command ) {
    case com_flash :
        args->com_flash_data.force = 0;
        args->com_flash_data.segment = mem_flash;
        break;
    case com_launch :
        args->com_launch_config.noreset = 0;
        break;
    case com_dump :
        args->com_read_data.segment = mem_flash;
        args->com_flash_data.force = 0;
        break;
    case com_bin2hex :
        args->com_convert_data.segment = mem_flash;
        break;
    default :
        break;
    }

    if( 0 != assign_global_options(args, argc, argv) ) {
        status = -5;
        goto done;
    }

    if( 0 != assign_command_options(args, argc, argv) ) {
        status = -6;
        goto done;
    }

    /* Make sure there weren't any *extra* options. */
    for( i = 0; i < argc; i++ ) {
        if( '\0' != *argv[i] ) {
            fprintf( stderr, "unrecognized parameter\n" );
            status = -7;
            goto done;
        }
    }

    /* if this is a flash command, restore the filename */
    if( (com_flash == args->command) || (com_eflash == args->command)
            || (com_user == args->command) ) {
        if( 0 == args->com_flash_data.file ) {
// TODO : it should be ok to not have a filename if --serial=hexdigits:offset is
// provided, this should be implemented.. in fact, given that most of this
// program is written to use a single command by it self, this probably should
// be separated out as a new command.  The caveat is if data is written to '\0'
// in the hex file, serialize will do nothing bc can't unwrite w/o erase
            fprintf( stderr, "flash filename is missing\n" );
            status = -8;
            goto done;
        }
        args->com_flash_data.file[0] = args->com_flash_data.original_first_char;
    }

    if( (com_bin2hex == args->command) || (com_hex2bin == args->command) ) {
        if( 0 == args->com_convert_data.file ) {
            fprintf( stderr, "conversion filename is missing\n" );
            status = -8;
            goto done;
        }
        args->com_convert_data.file[0] = args->com_convert_data.original_first_char;
    }

done:
    if( 1 < debug ) {
        print_args( args );
    }

    if(-3 == status ) {
        list_targets( LIST_STD );
    } else if( 0 != status ) {
        usage();
    }

    return status;
}
Ejemplo n.º 22
0
int
main(int argc, char **argv)
{
    unsigned u = 0;
    unsigned int num = 0;
    int input_eof = 0;
    unsigned table_rows = 0;
    unsigned table_columns = 0;
    unsigned current_row = 0;
    FILE * fileInp = 0;
    FILE * fileOut = 0;
    const char *aname = 0;
    unsigned int index = 0;

    print_version_details(argv[0],FALSE);
    process_args(argc,argv);
    print_args(argc,argv);

    if (!input_name ) {
        fprintf(stderr,"Input name required, not supplied.\n");
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }
    fileInp = fopen(input_name,"r");
    if (!fileInp) {
        fprintf(stderr,"Invalid input filename, could not open '%s'\n",
                input_name);
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }

    if (!output_name ) {
        fprintf(stderr,"Output name required, not supplied.\n");
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }
    fileOut = fopen(output_name,"w");
    if (!fileOut) {
        fprintf(stderr,"Invalid output filename, could not open: '%s'\n",
                output_name);
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }
    if ((standard_flag && extended_flag) ||
            (!standard_flag && !extended_flag)) {
        fprintf(stderr,"Invalid table type\n");
        fprintf(stderr,"Choose -e  or -s .\n");
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }

    if (standard_flag) {
        table_rows = STD_ATTR_TABLE_ROWS;
        table_columns = STD_ATTR_TABLE_COLUMNS;
    } else {
        table_rows = EXT_ATTR_TABLE_ROWS;
        table_columns = EXT_ATTR_TABLE_COLS;
    }

    input_eof = read_value(&num,fileInp);       /* 0xffffffff */
    if (IS_EOF == input_eof) {
        bad_line_input("Empty input file");
    }
    if (num != MAGIC_TOKEN_VALUE) {
        bad_line_input("Expected 0xffffffff");
    }

    /*  Generate main header, regardless of contents */
    fprintf(fileOut,"/* Generated code, do not edit. */\n");
    fprintf(fileOut,"/* Generated on %s  %s */\n",__DATE__,__TIME__);
    fprintf(fileOut,"\n/* BEGIN FILE */\n\n");

#ifdef HAVE_USAGE_TAG_ATTR
    /* Generate the data type to record the usage of the pairs tag-attr */
    if (standard_flag) {
        fprintf(fileOut,"#ifndef HAVE_USAGE_TAG_ATTR\n");
        fprintf(fileOut,"#define HAVE_USAGE_TAG_ATTR 1\n");
        fprintf(fileOut,"#endif /* HAVE_USAGE_TAG_ATTR */\n\n");
        fprintf(fileOut,"#ifdef HAVE_USAGE_TAG_ATTR\n");
        fprintf(fileOut,"#include \"dwarf.h\"\n");
        fprintf(fileOut,"#include \"libdwarf.h\"\n\n");
        fprintf(fileOut,"typedef struct {\n");
        fprintf(fileOut,"    unsigned int count; /* Attribute count */\n");
        fprintf(fileOut,"    Dwarf_Half attr;    /* Attribute value */\n");
        fprintf(fileOut,"} Usage_Tag_Attr;\n\n");
    }
#endif /* HAVE_USAGE_TAG_ATTR */

    while (!feof(stdin)) {
        unsigned int tag;
        unsigned int curcol = 0;
        unsigned int cur_attr = 0;
        unsigned int attr;

        input_eof = read_value(&tag,fileInp);
        if (IS_EOF == input_eof) {
            /* Reached normal eof */
            break;
        }
        if (standard_flag) {
            if (tag >= table_rows ) {
                bad_line_input("tag %d exceeds standard table size",tag);
            }
        } else {
            if (current_row >= table_rows) {
                bad_line_input("too many extended table rows.");
            }
            tag_attr_combination_table[current_row][0] = tag;
        }

        input_eof = read_value(&num,fileInp);
        if (IS_EOF == input_eof) {
            bad_line_input("Not terminated correctly..");
        }
        curcol = 1;
        cur_attr = 1;

#ifdef HAVE_USAGE_TAG_ATTR
        /* Check if we have duplicated tags */
        if (standard_flag) {
            if (tag_parents[tag]) {
                bad_line_input("tag 0x%02x value already defined",tag);
            }
            tag_parents[tag] = tag;

            /* Clear out the working attribute vector */
            memset(tag_attr_vector,0,DW_AT_last * sizeof(Dwarf_Half));
        }
#endif /* HAVE_USAGE_TAG_ATTR */

        while (num != MAGIC_TOKEN_VALUE) {
            if (standard_flag) {
                unsigned idx = num / BITS_PER_WORD;
                unsigned bit = num % BITS_PER_WORD;

                if (idx >= table_columns) {
                    char msg[200];
                    snprintf(msg, sizeof(msg),
                             "too many attributes a: table incomplete "
                             "index %d cols %d.",idx,table_columns);
                    bad_line_input(msg);
                }
                tag_attr_combination_table[tag][idx] |= (1 << bit);
            } else {
                if (curcol >= table_columns) {
                    char msg[200];
                    snprintf(msg, sizeof(msg),
                             "too many attributes b: table incomplete "
                             "index %d cols %d.",curcol,table_columns);
                    bad_line_input(msg);
                }
                tag_attr_combination_table[current_row][curcol] = num;
                curcol++;

            }

#ifdef HAVE_USAGE_TAG_ATTR
            /* Record the usage only for standard tables */
            if (standard_flag) {
                /* Add attribute to current tag */
                if (cur_attr >= DW_AT_last) {
                    char msg[200];
                    snprintf(msg, sizeof(msg),
                             "too many attributes c: table incomplete "
                             "index %d cols %d.",cur_attr,DW_AT_last);
                    bad_line_input(msg);
                }
                /* Check for duplicated entries */
                if (tag_attr_vector[cur_attr]) {
                    bad_line_input("duplicated attributes: table incomplete.");
                }
                tag_attr_vector[cur_attr] = num;
                cur_attr++;
            }
#endif /* HAVE_USAGE_TAG_ATTR */

            input_eof = read_value(&num,fileInp);
            if (IS_EOF == input_eof) {
                bad_line_input("Not terminated correctly.");
            }
        }

#ifdef HAVE_USAGE_TAG_ATTR
        /* Generate the tag-attributes vector for current tag */
        if (standard_flag) {
            if (tag >= DW_TAG_last) {
                bad_line_input("tag 0x%02x exceeds standard table size",tag);
            }
            if (tag_children[tag]) {
                bad_line_input("tag 0x%02x already defined",tag);
            }
            tag_children[tag] = tag;
            /* Generate reference vector */
            aname = 0;
            dwarf_get_TAG_name(tag,&aname);
            fprintf(fileOut,"/* 0x%02x - %s */\n",tag,aname);
            fprintf(fileOut,
                    "static Usage_Tag_Attr tag_attr_%02x[] = {\n",tag);
            for (index = 1; index < cur_attr; ++index) {
                attr = tag_attr_vector[index];
                dwarf_get_AT_name(attr,&aname);
                fprintf(fileOut,"    {/* 0x%02x */  0, %s},\n",attr,aname);
            }
            fprintf(fileOut,"    {/* %4s */  0, 0}\n};\n\n"," ");
            /* Record allowed number of attributes */
            tag_attr_legal[tag] = cur_attr - 1;
        }
#endif /* HAVE_USAGE_TAG_ATTR */

        ++current_row;
    }

#ifdef HAVE_USAGE_TAG_ATTR
    /* Generate the parent of the individual vectors */
    if (standard_flag) {
        unsigned int tag;
        unsigned int legal;

        fprintf(fileOut,
                "static Usage_Tag_Attr *usage_tag_attr[] = {\n");
        for (index = 0; index < DW_TAG_last; ++index) {
            tag = tag_children[index];
            if (tag) {
                aname = 0;
                dwarf_get_TAG_name(tag,&aname);
                fprintf(fileOut,
                        "    tag_attr_%02x, /* 0x%02x - %s */\n",tag,tag,aname);
            } else {
                fprintf(fileOut,"    0,\n");
            }
        }
        fprintf(fileOut,"    0\n};\n\n");

        /* Generate table with allowed number of attributes */
        fprintf(fileOut,"typedef struct {\n");
        fprintf(fileOut,"    Dwarf_Small legal; /* Legal attributes */\n");
        fprintf(fileOut,"    Dwarf_Small found; /* Found attributes */\n");
        fprintf(fileOut,"} Rate_Tag_Attr;\n\n");
        fprintf(fileOut,
                "static Rate_Tag_Attr rate_tag_attr[] = {\n");
        for (tag = 0; tag < DW_TAG_last; ++tag) {
            if (tag_children[tag]) {
                legal = tag_attr_legal[tag];
                aname = 0;
                dwarf_get_TAG_name(tag,&aname);
                fprintf(fileOut,
                        "    {%2d, 0, /* 0x%02x - %s */},\n",legal,tag,aname);
            } else {
                fprintf(fileOut,"    {0, 0},\n");
            }
        }
        fprintf(fileOut,"    {0, 0}\n};\n\n");
        fprintf(fileOut,"#endif /* HAVE_USAGE_TAG_ATTR */\n\n");
    }
#endif /* HAVE_USAGE_TAG_ATTR */

    if (standard_flag) {
        fprintf(fileOut,"#define ATTR_TREE_ROW_COUNT %d\n\n",table_rows);
        fprintf(fileOut,"#define ATTR_TREE_COLUMN_COUNT %d\n\n",table_columns);
        fprintf(fileOut,
                "static unsigned int tag_attr_combination_table"
                "[ATTR_TREE_ROW_COUNT][ATTR_TREE_COLUMN_COUNT] = {\n");
    }
    else {
        fprintf(fileOut,"/* Common extensions */\n");
        fprintf(fileOut,"#define ATTR_TREE_EXT_ROW_COUNT %d\n\n",table_rows);
        fprintf(fileOut,"#define ATTR_TREE_EXT_COLUMN_COUNT %d\n\n",
                table_columns);
        fprintf(fileOut,
                "static unsigned int tag_attr_combination_ext_table"
                "[ATTR_TREE_EXT_ROW_COUNT][ATTR_TREE_EXT_COLUMN_COUNT] = {\n");
    }

    for (u = 0; u < table_rows; u++) {
        unsigned j = 0;
        const char *name = 0;
        if (standard_flag) {
            dwarf_get_TAG_name(u,&name);
            fprintf(fileOut,"/* 0x%02x - %-37s*/\n",u,name);
        } else {
            unsigned k = tag_attr_combination_table[u][0];
            dwarf_get_TAG_name(k,&name);
            fprintf(fileOut,"/* 0x%02x - %-37s*/\n",k,name);
        }
        fprintf(fileOut,"    { ");
        for (j = 0; j < table_columns; ++j ) {
            fprintf(fileOut,"0x%08x,",tag_attr_combination_table[u][j]);
        }
        fprintf(fileOut,"},\n");
    }
    fprintf(fileOut,"};\n");
    fprintf(fileOut,"\n/* END FILE */\n");
    fclose(fileInp);
    fclose(fileOut);
    return (0);
}
Ejemplo n.º 23
0
int
main(int argc, char **argv)
{
    unsigned u = 0;
    unsigned int num = 0;
    int input_eof = 0;
    unsigned table_rows = 0;
    unsigned table_columns = 0;
    unsigned current_row = 0;
    FILE * fileInp = 0;
    FILE * fileOut = 0;

    print_version_details(argv[0],FALSE);
    process_args(argc,argv);
    print_args(argc,argv);

    if (!input_name ) {
        fprintf(stderr,"Input name required, not supplied.\n");
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }
    fileInp = fopen(input_name,"r");
    if (!fileInp) {
        fprintf(stderr,"Invalid input filename, could not open '%s'\n",
            input_name);
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }


    if (!output_name ) {
        fprintf(stderr,"Output name required, not supplied.\n");
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }
    fileOut = fopen(output_name,"w");
    if (!fileOut) {
        fprintf(stderr,"Invalid output filename, could not open: '%s'\n",
            output_name);
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }
    if ((standard_flag && extended_flag) || 
        (!standard_flag && !extended_flag)) {
        fprintf(stderr,"Invalid table type\n");
        fprintf(stderr,"Choose -e  or -s .\n"); 
        print_usage_message(argv[0],usage);
        exit(FAILED);
    }


    if (standard_flag) {
        table_rows = STD_ATTR_TABLE_ROWS;
        table_columns = STD_ATTR_TABLE_COLUMNS;
    } else {
        table_rows = EXT_ATTR_TABLE_ROWS;
        table_columns = EXT_ATTR_TABLE_COLS;
    }

    input_eof = read_value(&num,fileInp);       /* 0xffffffff */
    if (IS_EOF == input_eof) {
        bad_line_input("Empty input file");
    }
    if (num != MAGIC_TOKEN_VALUE) {
        bad_line_input("Expected 0xffffffff");
    }
    while (!feof(stdin)) {
        unsigned int tag;
        unsigned int curcol = 0;

        input_eof = read_value(&tag,fileInp);
        if (IS_EOF == input_eof) {
            /* Reached normal eof */
            break;
        }
        if (standard_flag) {
            if (tag >= table_rows ) {
                bad_line_input("tag value exceeds standard table size");
            }
        } else {
            if (current_row >= table_rows) {
                bad_line_input("too many extended table rows.");
            }
            tag_attr_combination_table[current_row][0] = tag;
        }

        input_eof = read_value(&num,fileInp);
        if (IS_EOF == input_eof) {
            bad_line_input("Not terminated correctly..");
        }
        curcol = 1;
        while (num != MAGIC_TOKEN_VALUE) {
            if (standard_flag) {
                unsigned idx = num / BITS_PER_WORD;
                unsigned bit = num % BITS_PER_WORD;

                if (idx >= table_columns) {
                    bad_line_input
                        ("too many attributes: table incomplete.");
                }
                tag_attr_combination_table[tag][idx] |= (1 << bit);
            } else {
                if (curcol >= table_columns) {
                    bad_line_input("too many attributes: table incomplete.");
                } 
                tag_attr_combination_table[current_row][curcol] = num;
                curcol++;
                
            }
            input_eof = read_value(&num,fileInp);
            if (IS_EOF == input_eof) {
                bad_line_input("Not terminated correctly.");
            }
        }
        ++current_row;
    }
    fprintf(fileOut,"/* Generated code, do not edit. */\n");
    fprintf(fileOut,"/* Generated on %s  %s */\n",__DATE__,__TIME__);
    fprintf(fileOut,"\n/* BEGIN FILE */\n\n");
    if (standard_flag) {
        fprintf(fileOut,"#define ATTR_TREE_ROW_COUNT %d\n\n",table_rows);
        fprintf(fileOut,"#define ATTR_TREE_COLUMN_COUNT %d\n\n",table_columns);
        fprintf(fileOut,
            "static unsigned int tag_attr_combination_table"
            "[ATTR_TREE_ROW_COUNT][ATTR_TREE_COLUMN_COUNT] = {\n");
    }
    else {
        fprintf(fileOut,"/* Common extensions */\n");
        fprintf(fileOut,"#define ATTR_TREE_EXT_ROW_COUNT %d\n\n",table_rows);
        fprintf(fileOut,"#define ATTR_TREE_EXT_COLUMN_COUNT %d\n\n",
            table_columns);
        fprintf(fileOut,
            "static unsigned int tag_attr_combination_ext_table"
            "[ATTR_TREE_EXT_ROW_COUNT][ATTR_TREE_EXT_COLUMN_COUNT] = {\n");
    }

    for (u = 0; u < table_rows; u++) {
        unsigned j = 0;
        const char *name = 0;
        if (standard_flag) {
            dwarf_get_TAG_name(u,&name);
            fprintf(fileOut,"/* %u %-37s*/\n",u,name); 
        } else {
            unsigned k = tag_attr_combination_table[u][0];
            dwarf_get_TAG_name(k,&name);           
            fprintf(fileOut,"/* %u %-37s*/\n",k,name);
        }
        fprintf(fileOut,"    { ");
        for (j = 0; j < table_columns; ++j ) {
            fprintf(fileOut,"0x%08x,",tag_attr_combination_table[u][j]);
        }
        fprintf(fileOut,"},\n");
    }
    fprintf(fileOut,"};\n");
    fprintf(fileOut,"\n/* END FILE */\n");
    fclose(fileInp);
    fclose(fileOut);
    return (0);
}
Ejemplo n.º 24
0
int char_buffer::run_output_filter(int filter, int argc, char **argv)
{
  int pipedes[2];
  PID_T child_pid;
  int status;

  print_args(argc, argv);
  if (pipe(pipedes) < 0)
    sys_fatal("pipe");

#if MAY_FORK_CHILD_PROCESS
  // This is the UNIX process model.  To invoke our post-processor,
  // we must `fork' the current process.

  if ((child_pid = fork()) < 0)
    sys_fatal("fork");

  else if (child_pid == 0) {
    // This is the child process fork.  We redirect its `stdin' stream
    // to read data emerging from our pipe.  There is no point in saving,
    // since we won't be able to restore later!

    set_redirection(STDIN_FILENO, pipedes[0]);

    // The parent process will be writing this data, so we should release
    // the child's writeable handle on the pipe, since we have no use for it.

    if (close(pipedes[1]) < 0)
      sys_fatal("close");

    // The IMAGE_OUTPUT_FILTER needs special output redirection...

    if (filter == IMAGE_OUTPUT_FILTER) {
      // with BOTH `stdout' AND `stderr' diverted to files.

      set_redirection(STDOUT_FILENO, PS_OUTPUT_STREAM);
      set_redirection(STDERR_FILENO, REGION_OUTPUT_STREAM);
    }

    // Now we are ready to launch the output filter.

    execvp(argv[0], argv);

    // If we get to here then the `exec...' request for the output filter
    // failed.  Diagnose it and bail out.

    error("couldn't exec %1: %2", argv[0], strerror(errno), ((char *)0));
    fflush(stderr);	// just in case error() didn't
    exit(1);
  }

  else {
    // This is the parent process fork.  We will be writing data to the
    // filter pipeline, and the child will be reading it.  We have no further
    // use for our read handle on the pipe, and should close it.

    if (close(pipedes[0]) < 0)
      sys_fatal("close");

    // Now we redirect the `stdout' stream to the inlet end of the pipe,
    // and push out the appropiately formatted data to the filter.

    pipedes[1] = save_and_redirect(STDOUT_FILENO, pipedes[1]);
    emit_troff_output(DEVICE_FORMAT(filter));

    // After emitting all the data we close our connection to the inlet
    // end of the pipe so the child process will detect end of data.

    set_redirection(STDOUT_FILENO, pipedes[1]);

    // Finally, we must wait for the child process to complete.

    if (WAIT(&status, child_pid, _WAIT_CHILD) != child_pid)
      sys_fatal("wait");
  }

#elif MAY_SPAWN_ASYNCHRONOUS_CHILD

  // We do not have `fork', (or we prefer not to use it),
  // but asynchronous processes are allowed, passing data through pipes.
  // This should be ok for most Win32 systems and is preferred to `fork'
  // for starting child processes under Cygwin.

  // Before we start the post-processor we bind its inherited `stdin'
  // stream to the readable end of our pipe, saving our own `stdin' stream
  // in `pipedes[0]'.

  pipedes[0] = save_and_redirect(STDIN_FILENO, pipedes[0]);

  // for the Win32 model,
  // we need special provision for saving BOTH `stdout' and `stderr'.

  int saved_stdout = dup(STDOUT_FILENO);
  int saved_stderr = STDERR_FILENO;

  // The IMAGE_OUTPUT_FILTER needs special output redirection...

  if (filter == IMAGE_OUTPUT_FILTER) {
    // with BOTH `stdout' AND `stderr' diverted to files while saving a
    // duplicate handle for `stderr'.

    set_redirection(STDOUT_FILENO, PS_OUTPUT_STREAM);
    saved_stderr = save_and_redirect(STDERR_FILENO, REGION_OUTPUT_STREAM);
  }

  // We then use an asynchronous spawn request to start the post-processor.

  if ((child_pid = spawnvp(_P_NOWAIT, argv[0], argv)) < 0) {
    // Should the spawn request fail we issue a diagnostic and bail out.

    error("cannot spawn %1: %2", argv[0], strerror(errno), ((char *)0));
    exit(1);
  }

  // Once the post-processor has been started we revert our `stdin'
  // to its original saved source, which also closes the readable handle
  // for the pipe.

  set_redirection(STDIN_FILENO, pipedes[0]);

  // if we redirected `stderr', for use by the image post-processor,
  // then we also need to reinstate its original assignment.

  if (filter == IMAGE_OUTPUT_FILTER)
    set_redirection(STDERR_FILENO, saved_stderr);

  // Now we redirect the `stdout' stream to the inlet end of the pipe,
  // and push out the appropiately formatted data to the filter.

  set_redirection(STDOUT_FILENO, pipedes[1]);
  emit_troff_output(DEVICE_FORMAT(filter));

  // After emitting all the data we close our connection to the inlet
  // end of the pipe so the child process will detect end of data.

  set_redirection(STDOUT_FILENO, saved_stdout);

  // And finally, we must wait for the child process to complete.

  if (WAIT(&status, child_pid, _WAIT_CHILD) != child_pid)
    sys_fatal("wait");

#else /* can't do asynchronous pipes! */

  // TODO: code to support an MS-DOS style process model
  //        should go here

#endif /* MAY_FORK_CHILD_PROCESS or MAY_SPAWN_ASYNCHRONOUS_CHILD */

  return 0;
}
Ejemplo n.º 25
0
int main(int argc, char *argv[])
{
    int np=1, rank=0;
    int splitrank, splitsize;
    int rc = 0;
    nssi_service xfer_svc;

    int server_index=0;
    int rank_in_server=0;

    int transport_index=-1;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &np);

    MPI_Barrier(MPI_COMM_WORLD);

    Teuchos::oblackholestream blackhole;
    std::ostream &out = ( rank == 0 ? std::cout : blackhole );

    struct xfer_args args;

    const int num_io_methods = 8;
    const int io_method_vals[] = {
            XFER_WRITE_ENCODE_SYNC, XFER_WRITE_ENCODE_ASYNC,
            XFER_WRITE_RDMA_SYNC, XFER_WRITE_RDMA_ASYNC,
            XFER_READ_ENCODE_SYNC, XFER_READ_ENCODE_ASYNC,
            XFER_READ_RDMA_SYNC, XFER_READ_RDMA_ASYNC};
    const char * io_method_names[] = {
            "write-encode-sync", "write-encode-async",
            "write-rdma-sync", "write-rdma-async",
            "read-encode-sync", "read-encode-async",
            "read-rdma-sync", "read-rdma-async"};

    const int nssi_transport_list[] = {
            NSSI_RPC_PTL,
            NSSI_RPC_PTL,
            NSSI_RPC_IB,
            NSSI_RPC_IB,
            NSSI_RPC_GEMINI,
            NSSI_RPC_GEMINI,
            NSSI_RPC_BGPDCMF,
            NSSI_RPC_BGPDCMF,
            NSSI_RPC_BGQPAMI,
            NSSI_RPC_BGQPAMI,
            NSSI_RPC_MPI};

    const int num_nssi_transports = 11;
    const int nssi_transport_vals[] = {
            0,
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10
            };
    const char * nssi_transport_names[] = {
            "portals",
            "ptl",
            "infiniband",
            "ib",
            "gemini",
            "gni",
            "bgpdcmf",
            "dcmf",
            "bgqpami",
            "pami",
            "mpi"
    };


    // Initialize arguments
    args.transport=NSSI_DEFAULT_TRANSPORT;
    args.len = 1;
    args.delay = 1;
    args.io_method = XFER_WRITE_RDMA_SYNC;
    args.debug_level = LOG_WARN;
    args.num_trials = 1;
    args.num_reqs = 1;
    args.result_file_mode = "a";
    args.result_file = "";
    args.url_file = "";
    args.logfile = "";
    args.client_flag = true;
    args.server_flag = true;
    args.num_servers = 1;
    args.num_threads = 0;
    args.timeout = 500;
    args.num_retries = 5;
    args.validate_flag = true;
    args.kill_server_flag = true;
    args.block_distribution = true;


    bool success = true;

    /**
     * We make extensive use of the \ref Teuchos::CommandLineProcessor for command-line
     * options to control the behavior of the test code.   To evaluate performance,
     * the "num-trials", "num-reqs", and "len" options control the amount of data transferred
     * between client and server.  The "io-method" selects the type of data transfer.  The
     * server-url specifies the URL of the server.  If running as a server, the server-url
     * provides a recommended URL when initializing the network transport.
     */
    try {

        //out << Teuchos::Teuchos_Version() << std::endl << std::endl;

        // Creating an empty command line processor looks like:
        Teuchos::CommandLineProcessor parser;
        parser.setDocString(
                "This example program demonstrates a simple data-transfer service "
                "built using the NEtwork Scalable Service Interface (Nessie)."
        );

        /* To set and option, it must be given a name and default value.  Additionally,
           each option can be given a help std::string.  Although it is not necessary, a help
           std::string aids a users comprehension of the acceptable command line arguments.
           Some examples of setting command line options are:
         */

        parser.setOption("delay", &args.delay, "time(s) for client to wait for server to start" );
        parser.setOption("timeout", &args.timeout, "time(ms) to wait for server to respond" );
        parser.setOption("server", "no-server", &args.server_flag, "Run the server" );
        parser.setOption("client", "no-client", &args.client_flag, "Run the client");
        parser.setOption("len", &args.len, "The number of structures in an input buffer");
        parser.setOption("debug",(int*)(&args.debug_level), "Debug level");
        parser.setOption("logfile", &args.logfile, "log file");
        parser.setOption("num-trials", &args.num_trials, "Number of trials (experiments)");
        parser.setOption("num-reqs", &args.num_reqs, "Number of reqs/trial");
        parser.setOption("result-file", &args.result_file, "Where to store results");
        parser.setOption("result-file-mode", &args.result_file_mode, "Write mode for the result");
        parser.setOption("server-url-file", &args.url_file, "File that has URL client uses to find server");
        parser.setOption("validate", "no-validate", &args.validate_flag, "Validate the data");
        parser.setOption("num-servers", &args.num_servers, "Number of server processes");
        parser.setOption("num-threads", &args.num_threads, "Number of threads used by each server process");
        parser.setOption("kill-server", "no-kill-server", &args.kill_server_flag, "Kill the server at the end of the experiment");
        parser.setOption("block-distribution", "rr-distribution", &args.block_distribution,
                "Use a block distribution scheme to assign clients to servers");

        // Set an enumeration command line option for the io_method
        parser.setOption("io-method", &args.io_method, num_io_methods, io_method_vals, io_method_names,
                "I/O Methods for the example: \n"
                "\t\t\twrite-encode-sync : Write data through the RPC args, synchronous\n"
                "\t\t\twrite-encode-async: Write data through the RPC args - asynchronous\n"
                "\t\t\twrite-rdma-sync : Write data using RDMA (server pulls) - synchronous\n"
                "\t\t\twrite-rdma-async: Write data using RDMA (server pulls) - asynchronous\n"
                "\t\t\tread-encode-sync : Read data through the RPC result - synchronous\n"
                "\t\t\tread-encode-async: Read data through the RPC result - asynchronous\n"
                "\t\t\tread-rdma-sync : Read data using RDMA (server puts) - synchronous\n"
                "\t\t\tread-rdma-async: Read data using RDMA (server puts) - asynchronous");


        // Set an enumeration command line option for the NNTI transport
        parser.setOption("transport", &transport_index, num_nssi_transports, nssi_transport_vals, nssi_transport_names,
                "NSSI transports (not all are available on every platform): \n"
                "\t\t\tportals|ptl    : Cray or Schutt\n"
                "\t\t\tinfiniband|ib  : libibverbs\n"
                "\t\t\tgemini|gni     : Cray libugni (Gemini or Aries)\n"
                "\t\t\tbgpdcmf|dcmf   : IBM BG/P DCMF\n"
                "\t\t\tbgqpami|pami   : IBM BG/Q PAMI\n"
                "\t\t\tmpi            : isend/irecv implementation\n"
                );



        /* There are also two methods that control the behavior of the
           command line processor.  First, for the command line processor to
           allow an unrecognized a command line option to be ignored (and
           only have a warning printed), use:
         */
        parser.recogniseAllOptions(true);

        /* Second, by default, if the parser finds a command line option it
           doesn't recognize or finds the --help option, it will throw an
           std::exception.  If you want prevent a command line processor from
           throwing an std::exception (which is important in this program since
           we don't have an try/catch around this) when it encounters a
           unrecognized option or help is printed, use:
         */
        parser.throwExceptions(false);

        /* We now parse the command line where argc and argv are passed to
           the parse method.  Note that since we have turned off std::exception
           throwing above we had better grab the return argument so that
           we can see what happened and act accordingly.
         */
        Teuchos::CommandLineProcessor::EParseCommandLineReturn parseReturn= parser.parse( argc, argv );

        if( parseReturn == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED ) {
            return 0;
        }

        if( parseReturn != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL   ) {
            return 1; // Error!

        }

        // Here is where you would use these command line arguments but for this example program
        // we will just print the help message with the new values of the command-line arguments.
        //if (rank == 0)
        //    out << "\nPrinting help message with new values of command-line arguments ...\n\n";

        //parser.printHelpMessage(argv[0],out);

    }

    TEUCHOS_STANDARD_CATCH_STATEMENTS(true,std::cerr,success);

    log_debug(args.debug_level, "transport_index=%d", transport_index);
    if (transport_index > -1) {
    	args.transport     =nssi_transport_list[transport_index];
    	args.transport_name=std::string(nssi_transport_names[transport_index]);
    }
	args.io_method_name=std::string(io_method_names[args.io_method]);

    log_debug(args.debug_level, "%d: Finished processing arguments", rank);


    if (!success) {
        MPI_Abort(MPI_COMM_WORLD, 1);
    }

    if (!args.server_flag && args.client_flag) {
        /* initialize logger */
        if (args.logfile.empty()) {
            logger_init(args.debug_level, NULL);
        } else {
            char fn[1024];
            sprintf(fn, "%s.client.%03d.log", args.logfile.c_str(), rank);
            logger_init(args.debug_level, fn);
        }
    } else if (args.server_flag && !args.client_flag) {
        /* initialize logger */
        if (args.logfile.empty()) {
            logger_init(args.debug_level, NULL);
        } else {
            char fn[1024];
            sprintf(fn, "%s.server.%03d.log", args.logfile.c_str(), rank);
            logger_init(args.debug_level, fn);
        }
    } else if (args.server_flag && args.client_flag) {
        /* initialize logger */
        if (args.logfile.empty()) {
            logger_init(args.debug_level, NULL);
        } else {
            char fn[1024];
            sprintf(fn, "%s.%03d.log", args.logfile.c_str(), rank);
            logger_init(args.debug_level, fn);
        }
    }

    log_level debug_level = args.debug_level;

    // Communicator used for both client and server (may split if using client and server)
    MPI_Comm comm;

    log_debug(debug_level, "%d: Starting xfer-service test", rank);

#ifdef TRIOS_ENABLE_COMMSPLITTER
    if (args.transport == NSSI_RPC_MPI) {
        MPI_Pcontrol(0);
    }
#endif

    /**
     * Since this test can be run as a server, client, or both, we need to play some fancy
     * MPI games to get the communicators working correctly.  If we're executing as both
     * a client and a server, we split the communicator so that the client thinks its
     * running by itself.
     */
    int color = 0;  // color=0-->server, color=1-->client
    if (args.client_flag && args.server_flag) {
        if (np < 2) {
            log_error(debug_level, "Must use at least 2 MPI processes for client and server mode");
            MPI_Abort(MPI_COMM_WORLD, -1);
        }

        // Split the communicators. Put all the servers as the first ranks.
        if (rank < args.num_servers) {
            color = 0;
            log_debug(debug_level, "rank=%d is a server", rank);
        }
        else {
            color = 1;  // all others are clients
            log_debug(debug_level, "rank=%d is a client", rank);
        }

        MPI_Comm_split(MPI_COMM_WORLD, color, rank, &comm);
    }
    else {
        if (args.client_flag) {
            color=1;
            log_debug(debug_level, "rank=%d is a client", rank);
        }
        else if (args.server_flag) {
            color=0;
            log_debug(debug_level, "rank=%d is a server", rank);
        }
        else {
            log_error(debug_level, "Must be either a client or a server");
            MPI_Abort(MPI_COMM_WORLD, -1);
        }
        MPI_Comm_split(MPI_COMM_WORLD, color, rank, &comm);
    }

    MPI_Comm_rank(comm, &splitrank);
    MPI_Comm_size(comm, &splitsize);

    log_debug(debug_level, "%d: Finished splitting communicators", rank);

    /**
     * Initialize the Nessie interface by specifying a transport, encoding scheme, and a
     * recommended URL.  \ref NSSI_DEFAULT_TRANSPORT is usually the best choice, since it
     * is often the case that only one type of transport exists on a particular platform.
     * Currently supported transports are \ref NSSI_RPC_PTL, \ref NSSI_RPC_GNI, and
     * \ref NSSI_RPC_IB.  We only support one type of encoding scheme so NSSI_DEFAULT_ENCODE
     * should always be used for the second argument.   The URL can be specified (as we did for
     * the server, or NULL (as we did for the client).  This is a recommended value.  Use the
     * \ref nssi_get_url function to find the actual value.
     */
    nssi_rpc_init((nssi_rpc_transport)args.transport, NSSI_DEFAULT_ENCODE, NULL);

    // Get the Server URL
    std::string my_url(NSSI_URL_LEN, '\0');
    nssi_get_url((nssi_rpc_transport)args.transport, &my_url[0], NSSI_URL_LEN);

    // If running as both client and server, gather and distribute
    // the server URLs to all the clients.
    if (args.server_flag && args.client_flag) {

        std::string all_urls;

        // This needs to be a vector of chars, not a string
        all_urls.resize(args.num_servers * NSSI_URL_LEN, '\0');

        // Have servers gather their URLs
        if (color == 0) {
            assert(args.num_servers == splitsize);  // these should be equal

            log_debug(debug_level, "%d: Gathering urls: my_url=%s", rank, my_url.c_str());

            // gather all urls to rank 0 of the server comm (also rank 0 of MPI_COMM_WORLD)
            MPI_Gather(&my_url[0], NSSI_URL_LEN, MPI_CHAR,
                    &all_urls[0], NSSI_URL_LEN, MPI_CHAR, 0, comm);
        }

        // broadcast the full set of server urls to all processes
        MPI_Bcast(&all_urls[0], all_urls.size(), MPI_CHAR, 0, MPI_COMM_WORLD);

        log_debug(debug_level, "%d: Bcast urls, urls.size=%d", rank, all_urls.size());

        if (color == 1) {

            // For block distribution scheme use the utility function (in xfer_util.cpp)
            if (args.block_distribution) {
                // Use this utility function to calculate the server_index
                xfer_block_partition(args.num_servers, splitsize, splitrank, &server_index, &rank_in_server);
            }

            // Use a simple round robin distribution scheme
            else {
                server_index   = splitrank % args.num_servers;
                rank_in_server = splitrank / args.num_servers;
            }

            // Copy the server url out of the list of urls
            int offset = server_index * NSSI_URL_LEN;

            args.server_url = all_urls.substr(offset, NSSI_URL_LEN);

            log_debug(debug_level, "client %d assigned to server \"%s\"", splitrank, args.server_url.c_str());
        }


        log_debug(debug_level, "%d: Finished distributing server urls, server_url=%s", rank, args.server_url.c_str());
    }

    // If running as a client only, have to get the list of servers from the urlfile.
    else if (!args.server_flag && args.client_flag){

        sleep(args.delay);  // give server time to get started

        std::vector< std::string > urlbuf;
        xfer_read_server_url_file(args.url_file.c_str(), urlbuf, comm);
        args.num_servers = urlbuf.size();

        // For block distribution scheme use the utility function (in xfer_util.cpp)
        if (args.block_distribution) {
            // Use this utility function to calculate the server_index
            xfer_block_partition(args.num_servers, splitsize, splitrank, &server_index, &rank_in_server);
        }

        // Use a simple round robin distribution scheme
        else {
            server_index   = splitrank % args.num_servers;
            rank_in_server = splitrank / args.num_servers;
        }

        args.server_url = urlbuf[server_index];
        log_debug(debug_level, "client %d assigned to server \"%s\"", splitrank, args.server_url.c_str());
    }

    else if (args.server_flag && !args.client_flag) {
        args.server_url = my_url;

        if (args.url_file.empty()) {
            log_error(debug_level, "Must set --url-file");
            MPI_Abort(MPI_COMM_WORLD, -1);
        }

        xfer_write_server_url_file(args.url_file.c_str(), my_url.c_str(), comm);
    }

    // Set the debug level for the xfer service.
    xfer_debug_level = args.debug_level;

    // Print the arguments after they've all been set.
    log_debug(debug_level, "%d: server_url=%s", rank, args.server_url.c_str());

    print_args(out, args, "%");

    log_debug(debug_level, "server_url=%s", args.server_url.c_str());

    //------------------------------------------------------------------------------
    /** If we're running this job with a server, the server always executes on node 0.
     *  In this example, the server is a single process.
     */
    if (color == 0) {
        rc = xfer_server_main((nssi_rpc_transport)args.transport, args.num_threads, comm);
        log_debug(debug_level, "Server is finished");
    }

    // ------------------------------------------------------------------------------
     /**  The parallel client will execute this branch.  The root node, node 0, of the client connects
      *   connects with the server, using the \ref nssi_get_service function.  Then the root
      *   broadcasts the service description to the other clients before starting the main
      *   loop of the client code by calling \ref xfer_client_main.
      */
    else {
        int i;
        int client_rank;

        // get rank within the client communicator
        MPI_Comm_rank(comm, &client_rank);

        nssi_init((nssi_rpc_transport)args.transport);

        // Only one process needs to connect to the service
        // TODO: Make get_service a collective call (some transports do not need a connection)
        //if (client_rank == 0) {
        {


            // connect to remote server
            for (i=0; i < args.num_retries; i++) {
                log_debug(debug_level, "Try to connect to server: attempt #%d, url=%s", i, args.server_url.c_str());
                rc=nssi_get_service((nssi_rpc_transport)args.transport, args.server_url.c_str(), args.timeout, &xfer_svc);
                if (rc == NSSI_OK)
                    break;
                else if (rc != NSSI_ETIMEDOUT) {
                    log_error(xfer_debug_level, "could not get svc description: %s",
                            nssi_err_str(rc));
                    break;
                }
            }
        }

        // wait for all the clients to connect
        MPI_Barrier(comm);

        //MPI_Bcast(&rc, 1, MPI_INT, 0, comm);

        if (rc == NSSI_OK) {
            if (client_rank == 0) log_debug(debug_level, "Connected to service on attempt %d\n", i);

            // Broadcast the service description to the other clients
            //log_debug(xfer_debug_level, "Bcasting svc to other clients");
            //MPI_Bcast(&xfer_svc, sizeof(nssi_service), MPI_BYTE, 0, comm);

            log_debug(debug_level, "Starting client main");
            // Start the client code
            xfer_client_main(args, xfer_svc, comm);


            MPI_Barrier(comm);

            // Tell one of the clients to kill the server
            if ((args.kill_server_flag) && (rank_in_server == 0)) {
                log_debug(debug_level, "%d: Halting xfer service", rank);
                rc = nssi_kill(&xfer_svc, 0, 5000);
            }
            rc=nssi_free_service((nssi_rpc_transport)args.transport, &xfer_svc);
            if (rc != NSSI_OK) {
                log_error(xfer_debug_level, "could not free svc description: %s",
                        nssi_err_str(rc));
            }
        }

        else {
            if (client_rank == 0)
                log_error(debug_level, "Failed to connect to service after %d attempts: ABORTING", i);
            success = false;
            //MPI_Abort(MPI_COMM_WORLD, -1);
        }

        nssi_fini((nssi_rpc_transport)args.transport);

    }

    log_debug(debug_level, "%d: clean up nssi", rank);
    MPI_Barrier(MPI_COMM_WORLD);

    // Clean up nssi_rpc
    rc = nssi_rpc_fini((nssi_rpc_transport)args.transport);
    if (rc != NSSI_OK)
        log_error(debug_level, "Error in nssi_rpc_fini");

    log_debug(debug_level, "%d: MPI_Finalize()", rank);
    MPI_Finalize();

    logger_fini();

    if(success && (rc == NSSI_OK))
    	out << "\nEnd Result: TEST PASSED" << std::endl;
    else
    	out << "\nEnd Result: TEST FAILED" << std::endl;

    return ((success && (rc==NSSI_OK)) ? 0 : 1 );
}
Ejemplo n.º 26
0
int main(int argc, char *argv[])
{
    int np=1, rank=0;
    int splitrank, splitsize;
    int rc = 0;
    nssi_service multicast_svc[2];

    int transport_index=-1;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &np);

    MPI_Barrier(MPI_COMM_WORLD);

    Teuchos::oblackholestream blackhole;
    std::ostream &out = ( rank == 0 ? std::cout : blackhole );

    struct multicast_args args;

    const int num_io_methods = 6;
    const int io_method_vals[] = {
            MULTICAST_EMPTY_REQUEST_SYNC, MULTICAST_EMPTY_REQUEST_ASYNC,
            MULTICAST_GET_SYNC,           MULTICAST_GET_ASYNC,
            MULTICAST_PUT_SYNC,           MULTICAST_PUT_ASYNC};
    const char * io_method_names[] = {
            "empty-request-sync", "empty-request-async",
            "get-sync",           "get-async",
            "put-sync",           "put-async"};

    const int nssi_transport_list[] = {
            NSSI_RPC_PTL,
            NSSI_RPC_PTL,
            NSSI_RPC_IB,
            NSSI_RPC_IB,
            NSSI_RPC_GEMINI,
            NSSI_RPC_GEMINI,
            NSSI_RPC_BGPDCMF,
            NSSI_RPC_BGPDCMF,
            NSSI_RPC_BGQPAMI,
            NSSI_RPC_BGQPAMI,
            NSSI_RPC_MPI};

    const int num_nssi_transports = 11;
    const int nssi_transport_vals[] = {
            0,
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10
            };
    const char * nssi_transport_names[] = {
            "portals",
            "ptl",
            "infiniband",
            "ib",
            "gemini",
            "gni",
            "bgpdcmf",
            "dcmf",
            "bgqpami",
            "pami",
            "mpi"
    };


    // Initialize arguments
    args.transport=NSSI_DEFAULT_TRANSPORT;
    args.delay = 1;
    args.io_method = MULTICAST_EMPTY_REQUEST_SYNC;
    args.debug_level = LOG_WARN;
    args.num_trials = 1;
    args.num_reqs = 1;
    args.len = 1;
    args.result_file_mode = "a";
    args.result_file = "";
    args.url_file[0] = "";
    args.url_file[1] = "";
    args.logfile = "";
    args.client_flag = true;
    args.server_flag = true;
    args.timeout = 500;
    args.num_retries = 5;
    args.validate_flag = true;
    args.server_url[0] = "";
    args.server_url[1] = "";

    bool success = true;

    /**
     * We make extensive use of the \ref Teuchos::CommandLineProcessor for command-line
     * options to control the behavior of the test code.   To evaluate performance,
     * the "num-trials", "num-reqs", and "len" options control the amount of data transferred
     * between client and server.  The "io-method" selects the type of data transfer.  The
     * server-url specifies the URL of the server.  If running as a server, the server-url
     * provides a recommended URL when initializing the network transport.
     */
    try {

        //out << Teuchos::Teuchos_Version() << std::endl << std::endl;

        // Creating an empty command line processor looks like:
        Teuchos::CommandLineProcessor parser;
        parser.setDocString(
                "This example program demonstrates a simple data-transfer service "
                "built using the NEtwork Scalable Service Interface (Nessie)."
        );

        /* To set and option, it must be given a name and default value.  Additionally,
           each option can be given a help std::string.  Although it is not necessary, a help
           std::string aids a users comprehension of the acceptable command line arguments.
           Some examples of setting command line options are:
         */

        parser.setOption("delay", &args.delay, "time(s) for client to wait for server to start" );
        parser.setOption("timeout", &args.timeout, "time(ms) to wait for server to respond" );
        parser.setOption("server", "no-server", &args.server_flag, "Run the server" );
        parser.setOption("client", "no-client", &args.client_flag, "Run the client");
        parser.setOption("len", &args.len, "The number of structures in an input buffer");
        parser.setOption("debug",(int*)(&args.debug_level), "Debug level");
        parser.setOption("logfile", &args.logfile, "log file");
        parser.setOption("num-trials", &args.num_trials, "Number of trials (experiments)");
        parser.setOption("num-reqs", &args.num_reqs, "Number of reqs/trial");
        parser.setOption("result-file", &args.result_file, "Where to store results");
        parser.setOption("result-file-mode", &args.result_file_mode, "Write mode for the result");
        parser.setOption("server-url-1", &args.server_url[0], "URL client uses to find the server 1");
        parser.setOption("server-url-2", &args.server_url[1], "URL client uses to find the server 2");
        parser.setOption("server-url-file-1", &args.url_file[0], "File that has URL client uses to find server 1");
        parser.setOption("server-url-file-2", &args.url_file[1], "File that has URL client uses to find server 2");
        parser.setOption("validate", "no-validate", &args.validate_flag, "Validate the data");

        // Set an enumeration command line option for the io_method

        parser.setOption("io-method", &args.io_method, num_io_methods, io_method_vals, io_method_names,
                "I/O Methods for the example: \n"
                "\t\t\tempty-request-sync : Send an empty request - synchronous\n"
                "\t\t\tempty-request-async: Send an empty request - asynchronous\n"
                "\t\t\tget-sync : Servers pull data from client - synchronous\n"
                "\t\t\tget-async: Servers pull data from client - asynchronous\n"
                "\t\t\tput-sync : Servers push data from client - synchronous\n"
                "\t\t\tput-async: Servers push data from client - asynchronous"
                );

        // Set an enumeration command line option for the NNTI transport
        parser.setOption("transport", &transport_index, num_nssi_transports, nssi_transport_vals, nssi_transport_names,
                "NSSI transports (not all are available on every platform): \n"
                "\t\t\tportals|ptl    : Cray or Schutt\n"
                "\t\t\tinfiniband|ib  : libibverbs\n"
                "\t\t\tgemini|gni     : Cray libugni (Gemini or Aries)\n"
                "\t\t\tbgpdcmf|dcmf   : IBM BG/P DCMF\n"
                "\t\t\tbgqpami|pami   : IBM BG/Q PAMI\n"
                "\t\t\tmpi            : isend/irecv implementation\n"
                );



        /* There are also two methods that control the behavior of the
           command line processor.  First, for the command line processor to
           allow an unrecognized a command line option to be ignored (and
           only have a warning printed), use:
         */
        parser.recogniseAllOptions(true);

        /* Second, by default, if the parser finds a command line option it
           doesn't recognize or finds the --help option, it will throw an
           std::exception.  If you want prevent a command line processor from
           throwing an std::exception (which is important in this program since
           we don't have an try/catch around this) when it encounters a
           unrecognized option or help is printed, use:
         */
        parser.throwExceptions(false);

        /* We now parse the command line where argc and argv are passed to
           the parse method.  Note that since we have turned off std::exception
           throwing above we had better grab the return argument so that
           we can see what happened and act accordingly.
         */
        Teuchos::CommandLineProcessor::EParseCommandLineReturn parseReturn= parser.parse( argc, argv );

        if( parseReturn == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED ) {
            return 0;
        }

        if( parseReturn != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL   ) {
            return 1; // Error!

        }

        // Here is where you would use these command line arguments but for this example program
        // we will just print the help message with the new values of the command-line arguments.
        //if (rank == 0)
        //    out << "\nPrinting help message with new values of command-line arguments ...\n\n";

        //parser.printHelpMessage(argv[0],out);

    }

    TEUCHOS_STANDARD_CATCH_STATEMENTS(true,std::cerr,success);

    log_debug(LOG_ALL, "transport_index=%d", transport_index);
    if (transport_index > -1) {
    	args.transport     =nssi_transport_list[transport_index];
    	args.transport_name=std::string(nssi_transport_names[transport_index]);
    }
    args.io_method_name=io_method_names[args.io_method];

    log_debug(args.debug_level, "%d: Finished processing arguments", rank);


    if (!success) {
        MPI_Abort(MPI_COMM_WORLD, 1);
    }


    if (!args.server_flag && args.client_flag) {
        /* initialize logger */
        if (args.logfile.empty()) {
            logger_init(args.debug_level, NULL);
        } else {
            char fn[1024];
            sprintf(fn, "%s.client.%03d.log", args.logfile.c_str(), rank);
            logger_init(args.debug_level, fn);
        }
    } else if (args.server_flag && !args.client_flag) {
        /* initialize logger */
        if (args.logfile.empty()) {
            logger_init(args.debug_level, NULL);
        } else {
            char fn[1024];
            sprintf(fn, "%s.server.%03d.log", args.logfile.c_str(), rank);
            logger_init(args.debug_level, fn);
        }
    } else if (args.server_flag && args.client_flag) {
        /* initialize logger */
        if (args.logfile.empty()) {
            logger_init(args.debug_level, NULL);
        } else {
            char fn[1024];
            sprintf(fn, "%s.%03d.log", args.logfile.c_str(), rank);
            logger_init(args.debug_level, fn);
        }
    }

    log_level debug_level = args.debug_level;

    // Communicator used for both client and server (may split if using client and server)
    MPI_Comm comm;

    log_debug(debug_level, "%d: Starting multicast-service test", rank);

    /**
     * Since this test can be run as a server, client, or both, we need to play some fancy
     * MPI games to get the communicators working correctly.  If we're executing as both
     * a client and a server, we split the communicator so that the client thinks its
     * running by itself.
     */
    if (args.client_flag && args.server_flag) {
        if (np < 3) {
            log_error(debug_level, "Must use at least 3 MPI processes for client and server mode");
            MPI_Abort(MPI_COMM_WORLD, -1);
        }

        // Split the communicators. Processors with color=0 are servers.

        int color = ((rank == 0)||(rank == 1)) ? 0 : 1; // two server
        MPI_Comm_split(MPI_COMM_WORLD, color, rank, &comm);

        MPI_Comm_rank(comm, &splitrank);
        MPI_Comm_size(comm, &splitsize);

        //    std::cout << "rank=" << rank << "/" << np << ", color=" << color <<
        //            ", new_rank=" << newrank << "/" << newsize << std::endl << std::endl;
        //
        //    std::cout << "my_url=" << my_url <<  ", server_url=" << args.server_url << std::endl;
    }
    else {
        MPI_Comm_dup(MPI_COMM_WORLD, &comm);
    }

    /**
     * Initialize the Nessie interface by specifying a transport, encoding scheme, and a
     * recommended URL.  \ref NSSI_DEFAULT_TRANSPORT is usually the best choice, since it
     * is often the case that only one type of transport exists on a particular platform.
     * Currently supported transports are \ref NSSI_RPC_PTL, \ref NSSI_RPC_GNI, and
     * \ref NSSI_RPC_IB.  We only support one type of encoding scheme so NSSI_DEFAULT_ENCODE
     * should always be used for the second argument.   The URL can be specified (as we did for
     * the server, or NULL (as we did for the client).  This is a recommended value.  Use the
     * \ref nssi_get_url function to find the actual value.
     */
    if (args.server_flag && !args.server_url[rank].empty()) {
        // use the server URL as suggested URL
        nssi_rpc_init((nssi_rpc_transport)args.transport, NSSI_DEFAULT_ENCODE, args.server_url[rank].c_str());
    }
    else {
        nssi_rpc_init((nssi_rpc_transport)args.transport, NSSI_DEFAULT_ENCODE, NULL);
    }

    // Get the Server URL
    std::string my_url(NSSI_URL_LEN, '\0');
    nssi_get_url((nssi_rpc_transport)args.transport, &my_url[0], NSSI_URL_LEN);

    // Broadcast the server URL to all the clients
    args.server_url[0].resize(NSSI_URL_LEN, '\0');
    args.server_url[1].resize(NSSI_URL_LEN, '\0');
    if (args.server_flag && args.client_flag) {
        args.server_url[0] = my_url;
        MPI_Bcast(&args.server_url[0][0], args.server_url[0].size(), MPI_CHAR, 0, MPI_COMM_WORLD);
        args.server_url[1] = my_url;
        MPI_Bcast(&args.server_url[1][0], args.server_url[1].size(), MPI_CHAR, 1, MPI_COMM_WORLD);
    }

    else if (!args.server_flag && args.client_flag){
        if (args.server_url[0].empty()) {

            // check to see if we're supposed to get the URL from a file
            if (!args.url_file[0].empty()) {
                // Fetch the server URL from a file
                sleep(1);
                log_debug(debug_level, "Reading from file %s", args.url_file[0].c_str());
                std::ifstream urlfile (args.url_file[0].c_str());
                if (urlfile.is_open()) {
                    if (urlfile.good())
                        getline(urlfile, args.server_url[0]);
                }
                else {
                    log_error(debug_level, "Failed to open server_url_file=%s", args.url_file[0].c_str());
                    exit(1);
                }
                urlfile.close();
                log_debug(debug_level, "URL = %s", args.server_url[0].c_str());
            }
            else {
                log_error(debug_level, "Need to set --server-url-1=[ADDR] or --server-url-file-1=[PATH]");
            }
        }
        if (args.server_url[1].empty()) {

            // check to see if we're supposed to get the URL from a file
            if (!args.url_file[1].empty()) {
                // Fetch the server URL from a file
                sleep(1);
                log_debug(debug_level, "Reading from file %s", args.url_file[1].c_str());
                std::ifstream urlfile (args.url_file[1].c_str());
                if (urlfile.is_open()) {
                    if (urlfile.good())
                        getline(urlfile, args.server_url[1]);
                }
                else {
                    log_error(debug_level, "Failed to open server_url_file=%s", args.url_file[1].c_str());
                    exit(1);
                }
                urlfile.close();
                log_debug(debug_level, "URL = %s", args.server_url[1].c_str());
            }
            else {
                log_error(debug_level, "Need to set --server-url-1=[ADDR] or --server-url-file-1=[PATH]");
            }
        }
    }

    else if (args.server_flag && !args.client_flag) {
        args.server_url[0] = my_url;
        // If the url_file value is set, write the url to a file
        if (!args.url_file[0].empty()) {
            std::ofstream urlfile (args.url_file[0].c_str());
            if (urlfile.is_open()) {
                urlfile << args.server_url[0].c_str() << std::endl;
            }
            urlfile.close();
            log_debug(debug_level, "Wrote url to file %s", args.url_file[0].c_str());
        }

        args.server_url[1] = my_url;
        // If the url_file value is set, write the url to a file
        if (!args.url_file[1].empty()) {
            std::ofstream urlfile (args.url_file[1].c_str());
            if (urlfile.is_open()) {
                urlfile << args.server_url[1].c_str() << std::endl;
            }
            urlfile.close();
            log_debug(debug_level, "Wrote url to file %s", args.url_file[1].c_str());
        }
    }



    // Set the debug level for the multicast service.
    multicast_debug_level = args.debug_level;

    // Print the arguments after they've all been set.
    print_args(out, args, "%");


    //------------------------------------------------------------------------------
    /** If we're running this job with a server, the server always executes on nodes 0 and 1.
     *  In this example, the server is two process.
     */
    if (args.server_flag && ((rank == 0)|(rank == 1))) {
        rc = multicast_server_main(args, comm);
        log_debug(debug_level, "Server is finished");
    }

    // ------------------------------------------------------------------------------
     /**  The parallel client will execute this branch.  The root node, nodes 0 and 1, of the client connects
      *   connects with the server, using the \ref nssi_get_service function.  Then the root
      *   broadcasts the service description to the other clients before starting the main
      *   loop of the client code by calling \ref multicast_client_main.
      */
    else {
        int i;
        int client_rank;

        // get rank within the client communicator
        MPI_Comm_rank(comm, &client_rank);

        nssi_init((nssi_rpc_transport)args.transport);

        // Only one process needs to connect to the service
        // TODO: Make get_service a collective call (some transports do not need a connection)
        //if (client_rank == 0) {
        {

            sleep(args.delay);  // give server time to get started

            // connect to remote server
            for (i=0; i < args.num_retries; i++) {
                log_debug(debug_level, "Try to connect to server: attempt #%d", i);
                rc=nssi_get_service((nssi_rpc_transport)args.transport, args.server_url[0].c_str(), args.timeout, &multicast_svc[0]);
                if (rc == NSSI_OK)
                    break;
                else if (rc != NSSI_ETIMEDOUT) {
                    log_error(multicast_debug_level, "could not get svc description: %s",
                            nssi_err_str(rc));
                    break;
                }
            }
            // connect to remote server
            for (i=0; i < args.num_retries; i++) {
                log_debug(debug_level, "Try to connect to server: attempt #%d", i);
                rc=nssi_get_service((nssi_rpc_transport)args.transport, args.server_url[1].c_str(), args.timeout, &multicast_svc[1]);
                if (rc == NSSI_OK)
                    break;
                else if (rc != NSSI_ETIMEDOUT) {
                    log_error(multicast_debug_level, "could not get svc description: %s",
                            nssi_err_str(rc));
                    break;
                }
            }
        }

        //MPI_Bcast(&rc, 1, MPI_INT, 0, comm);

        if (rc == NSSI_OK) {
            if (client_rank == 0) log_debug(debug_level, "Connected to service on attempt %d\n", i);

            // Broadcast the service description to the other clients
            //log_debug(multicast_debug_level, "Bcasting svc to other clients");
            //MPI_Bcast(&multicast_svc, sizeof(nssi_service), MPI_BYTE, 0, comm);

            log_debug(debug_level, "Starting client main");
            // Start the client code
            multicast_client_main(args, &multicast_svc[0], comm);


            MPI_Barrier(comm);

            // Tell one of the clients to kill the server
            if (client_rank == 0) {
                log_debug(debug_level, "%d: Halting multicast service", rank);
                rc = nssi_kill(&multicast_svc[0], 0, 5000);
                rc = nssi_kill(&multicast_svc[1], 0, 5000);
            }
        }

        else {
            if (client_rank == 0)
                log_error(debug_level, "Failed to connect to service after %d attempts: ABORTING", i);
            success = false;
            //MPI_Abort(MPI_COMM_WORLD, -1);
        }

        nssi_fini((nssi_rpc_transport)args.transport);

    }

    log_debug(debug_level, "%d: clean up nssi", rank);
    MPI_Barrier(MPI_COMM_WORLD);

    // Clean up nssi_rpc
    rc = nssi_rpc_fini((nssi_rpc_transport)args.transport);
    if (rc != NSSI_OK)
        log_error(debug_level, "Error in nssi_rpc_fini");

    log_debug(debug_level, "%d: MPI_Finalize()", rank);
    MPI_Finalize();

    logger_fini();

    if(success && (rc == NSSI_OK))
      out << "\nEnd Result: TEST PASSED" << std::endl;
    else
        out << "\nEnd Result: TEST FAILED" << std::endl;

    return ((success && (rc==NSSI_OK)) ? 0 : 1 );
}
Ejemplo n.º 27
0
/**
 * @parse_arguments
 * parameter arguments to_parse
 * return 0 ok, -1 wrong
 */
int parse_arguments(Args *to_parse, int argc, char **argv) {
	static struct option long_options[] = { 	//options
			{ "config_file", required_argument, NULL, 'c' }, //<yolo, imagenet..>.cfg
					{ "weights", required_argument, NULL, 'w' }, //<yolo, imagenet..>weights
					{ "iterations", required_argument, NULL, 'n' }, //log data iterations
					{ "generate", required_argument, NULL, 'g' }, //generate gold
					{ "img_list_path", required_argument, NULL, 'l' }, //data path list input
					{ "gold_inout", required_argument, NULL, 'd' },  //gold path
					{ "save_layers", required_argument, NULL, 's' }, //save layers
					{ "abft", required_argument, NULL, 'a'}, //abft
					{ "use_tensor_core", required_argument, NULL, 't'}, //tensor cores
					{ NULL, 0, NULL, 0 } };

	// loop over all of the options
	char ch;
	int option_index = 0;
	to_parse->generate_flag = 0;
	int max_args = 13;
	while ((ch = getopt_long(argc, argv, "c:w:n:g:l:d:s:a:t:", long_options,
			&option_index)) != -1 && --max_args) {

		// check to see if a single character or long option came through
		switch (ch) {

		case 'c': {
			to_parse->config_file = optarg;
			break;
		}
		case 'w': {
			to_parse->weights = optarg;
			break;
		}

		case 'n': {
			to_parse->iterations = atol(optarg);
			break;

		}
		case 'g': {
			to_parse->gold_inout = optarg;
			to_parse->generate_flag = 1;
			break;
		}
		case 'l': {
			to_parse->img_list_path = optarg;
			break;
		}

		case 'd': {
			to_parse->gold_inout = optarg;
			break;
		}

		case 's': {
			to_parse->save_layers = atoi(optarg);
			break;
		}

		case 'a': {
			printf("abft %s\n", optarg);
			to_parse->abft = atoi(optarg);
			break;
		}

		case 't': {
			to_parse->use_tensor_cores = atoi(optarg);
			break;
		}

		}

	}
	print_args(*to_parse);
	return check_args(to_parse);

}
Ejemplo n.º 28
0
Archivo: main.c Proyecto: f4exb/tnc1101
// ------------------------------------------------------------------------------------------------
int main (int argc, char **argv)
// ------------------------------------------------------------------------------------------------
{
    int i, nbytes;

    // unsolicited termination handling
    struct sigaction sa;
    // Catch all signals possible on process exit!
    for (i = 1; i < 64; i++) 
    {
        // skip SIGUSR2 for Wiring Pi
        if (i == 17)
            continue; 

        // These are uncatchable or harmless or we want a core dump (SEGV) 
        if (i != SIGKILL
            && i != SIGSEGV
            && i != SIGSTOP
            && i != SIGVTALRM
            && i != SIGWINCH
            && i != SIGPROF) 
        {
            memset(&sa, 0, sizeof(sa));
            sa.sa_handler = terminate;
            sigaction(i, &sa, NULL);
        }
    }

    // Set argument defaults
    init_args(&arguments); 

    // Parse arguments 
    argp_parse (&argp, argc, argv, 0, 0, &arguments);

    if (arguments.print_long_help)
    {
        print_long_help();
        return 0;
    }
    
    if (!arguments.usbacm_device)
    {
        arguments.usbacm_device = strdup("/dev/ttyACM2");
    }
    
    if (!arguments.serial_device)
    {
        arguments.serial_device = strdup("/var/ax25/axp2");
    }
    
    if (!arguments.bulk_filename)
    {
        arguments.bulk_filename = strdup("-");
    }

    set_serial_parameters(&serial_parms_ax25, arguments.serial_device, get_serial_speed(arguments.serial_speed, &arguments.serial_speed_n));
    set_serial_parameters(&serial_parms_usb,  arguments.usbacm_device, get_serial_speed(115200, &arguments.usb_speed_n));
    init_radio_parms(&radio_parms, &arguments);

    if (arguments.verbose_level > 0)
    {
        print_args(&arguments);
        print_radio_parms(&radio_parms);
        fprintf(stderr, "\n");
    }

    if (arguments.tnc_mode == TNC_KISS)
    {
        kiss_init(&arguments);
        kiss_run(&serial_parms_ax25, &serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_SLIP)
    {
        arguments.slip = 1;
        kiss_init(&arguments);
        kiss_run(&serial_parms_ax25, &serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_USB_ECHO) // This one does not need any access to the radio
    {
        usb_test_echo(&serial_parms_usb, &arguments);
    }
    else if (arguments.tnc_mode == TNC_RADIO_STATUS) 
    {
        print_radio_status(&serial_parms_usb, &arguments);
    }
    else if (arguments.tnc_mode == TNC_RADIO_INIT)
    {
        init_radio(&serial_parms_usb, &radio_parms, &arguments);

        if (nbytes < 0)
        {
            fprintf(stderr, "Error\n");
        }
    }
    else if (arguments.tnc_mode == TNC_TEST_TX)
    {
        radio_transmit_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX)
    {
        radio_receive_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_ECHO_TX)
    {
        radio_echo_test(&serial_parms_usb, &radio_parms, &arguments, 1);
    } 
    else if (arguments.tnc_mode == TNC_TEST_ECHO_RX)
    {
        radio_echo_test(&serial_parms_usb, &radio_parms, &arguments, 0);
    }
    else if (arguments.tnc_mode == TNC_TEST_TX_PACKET)
    {
        radio_packet_transmit_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX_PACKET)
    {
        radio_packet_receive_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX_PACKET_NON_BLOCKING)
    {
        radio_packet_receive_nb_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_BULK_TX)
    {
        file_bulk_transmit(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_BULK_RX)
    {
        file_bulk_receive(&serial_parms_usb, &radio_parms, &arguments);
    }

    close_serial(&serial_parms_usb);
    close_serial(&serial_parms_ax25);
    delete_args(&arguments);
    return 0;
}
Ejemplo n.º 29
0
int main ( int argc, char *argv[] )
{
    int      app_index, para_index, row_index;
    char     result[MAX_VALUE_LEN];
    int      ret = -1;
    char     tmp[128];

    int i = 0;
    char   app_result[100][MAX_VALUE_LEN];
    char     *p_result[100];
    for ( i = 0; i < 100; i++ )
    {
        app_result[i][0] = '\0';
        p_result[i] = app_result[i];
    }

    if ( argc > 1 && strcmp ( argv[1], "addtable" ) == 0 )
    {
        if ( ( ret = config_api_init_library() ) < 0 )
        {
            return -1;
        }

        app_index = atoi ( argv[2] );
        row_index = atoi ( argv[3] );

        ret = config_api_add_table_row ( app_index,row_index, &argv[4] );
        if ( ret == -1 )
        {
            printf ( "Error, config_api_add_table_row return -1.\n" );
            config_api_uninit_library ( );
            return -1;
        }
        config_api_write_to_flash ( );
        config_api_uninit_library ( );
        printf ( "Add table successfully\n" );
    }
    else
    {
        switch ( argc )
        {
            case 2:
                if ( strcmp ( argv[1], "dump" ) == 0 )
                {
                    if ( ( ret = config_api_init_library() ) < 0 )
                    {
                        return -1;
                    }

                    dump_para_table();
                    config_api_uninit_library ( );
                }
                else if ( strcmp ( argv[1], "release" ) == 0 )
                {
                    if ( config_api_release_library() == 0 )
                    {
                        printf ( "Release the cache space success! \n" );
                    }
                    else
                    {
                        printf ( "Fail to release the cache space\n" );
                    }
                }
                else if ( strcmp ( argv[1], "cat" ) == 0 )
                {
                    sprintf ( tmp, "cat %s", PARAMETER_FILE );
                    system ( tmp );
                }
                else
                {
                    print_args ();
                }
                break;
            case 3:
                if ( strcmp ( argv[1], "show" ) == 0 )
                {
                    if ( ( ret = config_api_init_library() ) < 0 )
                    {
                        return -1;
                    }

                    app_index = atoi ( argv[2] );
                    for ( i = 1; ; i++ )
                    {
                        ret = config_api_read_parameter ( app_index, i, result );
                        if ( ret )
                        {
                            if ( i == 1 )
                            {
                                printf ( "Can not find that ID\n" );
                            }
                            config_api_uninit_library ( );
                            return -1;
                        }
                        else
                        {
                            printf ( "%d = %s\n", i, result );
                        }
                    }
                    config_api_uninit_library ( );

                }
                else
                {
                    print_args ();
                }
                break;
            case 4:
                if ( strcmp ( argv[1], "read" ) == 0 )
                {
                    app_index = atoi ( argv[2] );
                    para_index = atoi ( argv[3] );
                    if ( ( ret = config_api_init_library() ) < 0 )
                    {
                        return -1;
                    }

                    ret = config_api_read_parameter ( app_index, para_index, result );

                    if ( ret == -1 )
                    {
                        printf ( "Error, config_api_read_parameter return -1.\n" );
                        config_api_uninit_library ( );
                        return -1;
                    }
                    printf ( "%s\n", result );
                    config_api_uninit_library ( );
                }
                else if ( strcmp ( argv[1], "deltable" ) == 0 )
                {
                    app_index = atoi ( argv[2] );
                    row_index = atoi ( argv[3] );

                    if ( ( ret = config_api_init_library() ) < 0 )
                    {
                        return -1;
                    }

                    ret = config_api_delete_table_row ( app_index, row_index );
                    if ( ret == -1 )
                    {
                        printf ( "Error, config_api_delete_table_row return -1.\n" );
                        config_api_uninit_library ( );
                        return -1;
                    }
                    printf ( " Delete the table successfully\n" );
                    config_api_write_to_flash ( );
                    config_api_uninit_library ( );

                }
                else if ( strcmp ( argv[1], "readtablegroup" ) == 0 )
                {
                    app_index = atoi ( argv[2] );
                    row_index = atoi ( argv[3] );

                    if ( ( ret = config_api_init_library() ) < 0 )
                    {
                        return -1;
                    }

                    ret = config_api_read_table_row ( app_index, row_index, p_result );

                    if ( ret )
                    {
                        printf ( "Fail to read table group\n" );
                        config_api_uninit_library ( );
                        return -1;
                    }
                    print_app_args ( p_result );
                    config_api_uninit_library ( );
                }
                else
                    print_args();
                break;
            case 5:
                if ( strcmp ( argv[1], "readtable" ) == 0 )
                {
                    app_index = atoi ( argv[2] );
                    row_index = atoi ( argv[3] );
                    para_index = atoi ( argv[4] );

                    if ( ( ret = config_api_init_library() ) < 0 )
                    {
                        return -1;
                    }

                    ret = config_api_read_table_parameter ( app_index, row_index, para_index, result );
                    if ( ret == -1 )
                    {
                        printf ( "Error, config_api_read_table_parameter return -1.\n" );
                        config_api_uninit_library ( );
                        return -1;
                    }
                    printf ( "%d = %s\n", para_index, result );

                    config_api_uninit_library ( );
                }
                else if ( strcmp ( argv[1], "write" ) == 0 )
                {
                    app_index = atoi ( argv[2] );
                    para_index = atoi ( argv[3] );

                    if ( ( ret = config_api_init_library() ) < 0 )
                    {
                        return -1;
                    }

                    ret = config_api_write_parameter ( app_index, para_index, argv[4] );
                    if ( ret == -1 )
                    {
                        printf ( "Error, config_api_write_parameter return -1.\n" );
                        config_api_uninit_library ( );
                        return -1;
                    }
                    printf ( "Write the parameter successfully\n" );
                    config_api_write_to_flash ( );

                    config_api_uninit_library ( );
                }
                else
                    print_args();
                break;

            case 6:
                if ( strcmp ( argv[1], "writetable" ) )
                {
                    print_args();
                    return -1;
                }
                app_index = atoi ( argv[2] );
                row_index = atoi ( argv[3] );
                para_index = atoi ( argv[4] );

                if ( ( ret = config_api_init_library() ) < 0 )
                {
                    return -1;
                }

                ret = config_api_write_table_parameter ( app_index, row_index, para_index, argv[5] );
                if ( ret == -1 )
                {
                    printf ( "Error, config_api_write_table_parameter return -1.\n" );
                    config_api_uninit_library ( );
                    return -1;
                }

                config_api_write_to_flash ( );
                printf ( "Write table parameter successfully\n" );

                config_api_uninit_library ( );
                break;

            default:
                print_args();
                break;
        }
    }

    return 0;
}
Ejemplo n.º 30
0
/*
 * Query and display information about the namespaces.
 */
void dyio_print_namespaces(dyio_t *d)
{
    int query_type, resp_type, num_args, num_resp;
    int num_spaces, ns, num_methods, m;
    uint8_t query[2], *args, *resp;
    char rpc[5];

    /* Query the number of namespaces. */
    dyio_call(d, PKT_GET, ID_BCS_CORE, "_nms", 0, 0);
    if (d->reply_len < 1) {
        printf("dyio-info: incorrect _nms reply: length %u bytes\n", d->reply_len);
        exit(-1);
    }
    num_spaces = d->reply[0];

    /* Print info about every namespace. */
    for (ns=0; ns<num_spaces; ns++) {
        query[0] = ns;
        dyio_call(d, PKT_GET, ID_BCS_CORE, "_nms", query, 1);
        if (d->reply_len < 1) {
            printf("dyio-info: incorrect _nms[%u] reply\n", ns);
            exit(-1);
        }
        printf("Namespace %u: %s\n", ns, d->reply);

        /* Print available methods. */
        num_methods = 1;
        for (m=0; m<num_methods; m++) {
            /* Get method name (RPC). */
            query[0] = ns;
            query[1] = m;
            dyio_call(d, PKT_GET, ID_BCS_RPC, "_rpc", query, 2);
            if (d->reply_len < 7) {
                printf("dyio-info: incorrect _rpc[%u] reply\n", ns);
                exit(-1);
            }
            num_methods = d->reply[2];
            rpc[0] = d->reply[3];
            rpc[1] = d->reply[4];
            rpc[2] = d->reply[5];
            rpc[3] = d->reply[6];
            rpc[4] = 0;

            /* Get method args. */
            query[0] = ns;
            query[1] = m;
            dyio_call(d, PKT_GET, ID_BCS_RPC, "args", query, 2);
            if (d->reply_len < 6) {
                printf("dyio-info: incorrect args[%u] reply\n", ns);
                exit(-1);
            }
            query_type = d->reply[2];
            num_args = d->reply[3];
            args = &d->reply[4];
            resp_type = d->reply[4 + num_args];
            num_resp = d->reply[5 + num_args];
            resp = &d->reply[6 + num_args];

            printf("    %s %s(", rpc, pkt_name(query_type));
            print_args(num_args, args);
            printf(") -> %s(", pkt_name(resp_type));
            print_args(num_resp, resp);
            printf(")\n");
        }
    }
}