示例#1
0
/*
 * datablob_parse - parse the keyctl data and fill in the
 * 		    payload and options structures
 *
 * On success returns 0, otherwise -EINVAL.
 */
static int datablob_parse(char *datablob, struct trusted_key_payload *p,
			  struct trusted_key_options *o)
{
	substring_t args[MAX_OPT_ARGS];
	long keylen;
	int ret = -EINVAL;
	int key_cmd;
	char *c;

	/* main command */
	c = strsep(&datablob, " \t");
	if (!c)
		return -EINVAL;
	key_cmd = match_token(c, key_tokens, args);
	switch (key_cmd) {
	case Opt_new:
		/* first argument is key size */
		c = strsep(&datablob, " \t");
		if (!c)
			return -EINVAL;
		ret = kstrtol(c, 10, &keylen);
		if (ret < 0 || keylen < MIN_KEY_SIZE || keylen > MAX_KEY_SIZE)
			return -EINVAL;
		p->key_len = keylen;
		ret = getoptions(datablob, p, o);
		if (ret < 0)
			return ret;
		ret = Opt_new;
		break;
	case Opt_load:
		/* first argument is sealed blob */
		c = strsep(&datablob, " \t");
		if (!c)
			return -EINVAL;
		p->blob_len = strlen(c) / 2;
		if (p->blob_len > MAX_BLOB_SIZE)
			return -EINVAL;
		ret = hex2bin(p->blob, c, p->blob_len);
		if (ret < 0)
			return -EINVAL;
		ret = getoptions(datablob, p, o);
		if (ret < 0)
			return ret;
		ret = Opt_load;
		break;
	case Opt_update:
		/* all arguments are options */
		ret = getoptions(datablob, p, o);
		if (ret < 0)
			return ret;
		ret = Opt_update;
		break;
	case Opt_err:
		return -EINVAL;
		break;
	}
	return ret;
}
示例#2
0
int main(int argc, char** argv)
{
  try {
    if (getoptions(argc, argv) != 0) 
      return 1;

    if (! temporary_dir.empty())
      ::setenv("TMPDIR_SPEC", temporary_dir.string().data(), 1);
    
    expgram::NGram ngram(ngram_file, shards, debug);
    
    utils::compress_ostream os(output_file);
    os << "ngram order: " << ngram.index.order() << '\n';
    for (int order = 1; order <= ngram.index.order(); ++ order)
      os << order << "-gram: " << std::setw(16) << ngram.index.ngram_size(order) << '\n';
    
    dump(os, "index",    ngram.stat_index()) << '\n';
    dump(os, "pointer",  ngram.stat_pointer()) << '\n';
    dump(os, "vocab",    ngram.stat_vocab()) << '\n';
    dump(os, "logprob",  ngram.stat_logprob()) << '\n';
    dump(os, "backoff",  ngram.stat_backoff()) << '\n';
    dump(os, "logbound", ngram.stat_logbound()) << '\n';
  }
  catch (std::exception& err) {
    std::cerr << "error: " << err.what() << std::endl;
    return 1;
  }
  return 0;
}
示例#3
0
void doinit()
{
  /* initializes variables */

  inputnumbers2(&spp, &nonodes2, 1);
  getoptions();
  if ( !usertree )
    nonodes2--;
  alloctree(&curtree.nodep, nonodes2);
  allocd(nonodes2, curtree.nodep);
  allocw(nonodes2, curtree.nodep);
  if (!usertree) {
    alloctree(&bestree.nodep, nonodes2);
    allocd(nonodes2, bestree.nodep);
    allocw(nonodes2, bestree.nodep);
    alloctree(&priortree.nodep, nonodes2);
    allocd(nonodes2, priortree.nodep);
    allocw(nonodes2, priortree.nodep);
    if (njumble > 1) {
      alloctree(&bestree2.nodep, nonodes2);
      allocd(nonodes2, bestree2.nodep);
      allocw(nonodes2, bestree2.nodep);
    }
  }
  allocrest();
}  /* doinit */
示例#4
0
/**********************************************************************//**
 *************************************************************************/
int main(int argc, char** argv) {
    
    // If no arguments have been passed, print the help text and quit
    if (argc==1) {
        Print_Help() ;
        return 0 ;
    }
    
    // Define the optional arguments
    struct option longopts[5] ;
    getoptions(longopts) ;
    
    // Parse the options
    std::map<std::string, double> options = parseoptions(argc, argv, longopts) ;
    
    // If no valid options were given, quit
    if (options.empty()) return 0 ;
    
    // Create a map to store the results
    std::map<std::string, double> results ;
    results["ra"] = 0.0 ;
    results["dec"]  = 0.0 ;
    
    // Convert the coordinates
    CECoordinates::Galactic2CIRS(options["glon"]*DD2R,
                                 options["glat"]*DD2R,
                                 &results["ra"],
                                 &results["dec"],
                                 CEDate(options["juliandate"])) ;
    
    // Print the results
    PrintResults(options, results) ;
    
    return 0 ;
}
示例#5
0
// 主程序
int main(int argc, char* argv[]) {
	// Get command line optins
	getoptions(argc, argv);

	// Load temp images to be matched
	IplImage* imgTemp = cvLoadImage(globalArgs.inputFiles[0]);

	// Get image from srcs[] which match temp image, and set ROI on it
	int nMatch;
	IplImage* imgSrc;
	if ((imgSrc = GetSourceImage(imgTemp, &nMatch)) == NULL) {
		if (globalArgs.verbosity)
			printf("[ERROR] Cannot match any temps. Abort.\n");

		return EXIT_FAILURE;
	}

	// Calculate match area of temp image
	int nMatchAreaSize = MatchAreaCount(imgSrc, imgTemp);

	// Calculate the change value
	int nChangeValue = ChangeValue(nMatchAreaSize, nMatch);
	if (globalArgs.verbosity) {
		printf(
				"MatchValue=%d YUAN\nMatchAreaRate=%f\nChangeValue = %d YUAN\n",
				full_value[nMatch],
				MatchAreaRate(nMatchAreaSize, nMatch),
				nChangeValue);
	}
	printf("%d", nChangeValue);
	cvReleaseImage(&imgSrc);
	cvReleaseImage(&imgTemp);

	return EXIT_SUCCESS;
}
示例#6
0
void doinput(int argc, Char *argv[])
{   /* reads the input data */
    getoptions();
    seqboot_inputnumbers();
    allocrest();
    inputoptions();
    seqboot_inputdata();
}  /* doinput */
示例#7
0
void doinit()
{
  /* initializes variables */
  restdist_inputnumbers();
  getoptions();
  if (printdata)
    fprintf(outfile, "\n %4ld Species, %4ld Sites\n", spp, sites);
  allocrest();
}  /* doinit */
示例#8
0
文件: options.c 项目: gsrr/Python
/* getopt might be declared in stdio.h */
static struct option *get_opt(const char *sect_name, const char *key)
{
	struct option *o = getoptions(sect_name);
	while (o) {
		if (!strcmp(key, opt_key(o)))
			return o;
		o = o->next;
	}
	return NULL;
}
示例#9
0
void doinit(U2::MemoryLocker& memLocker)
{
    /* initializes variables */

    //inputnumbers(&spp, &sites, &nonodes, 1);
    getoptions();
    if (printdata) {
        fprintf(outfile, "%2ld species, %3ld  sites\n", spp, sites);
    }
    allocrest(memLocker);
}  /* doinit */
int main(int argc, char** argv)
{
  utils::mpi_world  mpi_world(argc, argv);
  
  const int mpi_rank = MPI::COMM_WORLD.Get_rank();
  const int mpi_size = MPI::COMM_WORLD.Get_size();  
  
  try {
    if (getoptions(argc, argv) != 0) 
      return 1;

    if (! temporary_dir.empty())
      ::setenv("TMPDIR_SPEC", temporary_dir.string().data(), 1);
    
    if (ngram_file.empty() || ! boost::filesystem::exists(ngram_file))
      throw std::runtime_error("no ngram file?");
    if (output_file.empty())
      throw std::runtime_error("no output file?");
    if (ngram_file == output_file)
      throw std::runtime_error("dump to the same directory?");
    
    ngram_type ngram(debug);
    ngram.open_shard(ngram_file, mpi_rank);

    if (static_cast<int>(ngram.index.size()) != mpi_size)
      throw std::runtime_error("MPI universe size do not match with ngram shard size");
    
    utils::resource start;

    ngram_quantize(ngram);

    utils::resource end;
    
    if (debug && mpi_rank == 0)
      std::cerr << "quantize language model"
		<< " cpu time:  " << end.cpu_time() - start.cpu_time() 
		<< " user time: " << end.user_time() - start.user_time()
		<< std::endl;
    
    if (mpi_rank == 0)
      ngram.write_prepare(output_file);
    
    MPI::COMM_WORLD.Barrier();
    ngram.write_shard(output_file, mpi_rank);
  }
  catch (std::exception& err) {
    std::cerr << "error: "  << err.what() << std::endl;
    MPI::COMM_WORLD.Abort(1);
    return 1;
  }
  return 0;
}
示例#11
0
void doinit()
{
    /* initializes variables */

    inputnumbers(&spp, &chars, &nonodes, 1);
    words = chars / bits + 1;
    getoptions();
    if (printdata)
        fprintf(outfile, "%2ld species, %3ld characters\n", spp, chars);
    alloctree2(&treenode);
    setuptree2(treenode);
    allocrest();
}  /* doinit */
示例#12
0
void doinit()
{
  /* initializes variables */
  node *p;

  inputnumbers2(&spp, &nonodes2, 2);
  nonodes2 += (njoin ? 0 : 1);
  getoptions();
  alloctree(&curtree.nodep, nonodes2+1);
  p = curtree.nodep[nonodes2]->next->next;
  curtree.nodep[nonodes2]->next = curtree.nodep[nonodes2];
  free(p);
  allocrest();
}  /* doinit */
示例#13
0
int main (int argc, char ** argv){
	if(argc != 5)
		usage(1);

	getoptions(argc, argv);

	if(DEBUG){
		printf("port: %d\n", port);
		printf("fileOpt: %s\n", fileOpt);
	}

	int fd, bytesRead, fileSize, counter, i;

	char* inFile = "./tracker.txt";


	FILE * trackFp =fopen(inFile, "r");
	if(trackFp == NULL)	
		errorExit("bad Tracker");

	int numlines = numLines(inFile);
	if(DEBUG)
		printf("Numlines:%d\n", numlines);

	tracker * tracks = malloc ( numlines * sizeof(tracker));
	buildTracker(tracks, trackFp);
	//sort the tracks to make easier for later. Look @ compare to see sort order
	qsort (tracks, numlines, sizeof(tracks[0]), compare);
	if(DEBUG){
		for(i =0; i < numlines ; ++i)
			printTrack(tracks[i]);
	}

	//now we have all information in memory
	int numChunks = getNumChunks(tracks, fileOpt, numlines);
	printf("numChunks:%d\n", numChunks);
	sd = UDP_Open(-1);
	assert(sd > -1);

for(i=1; i <= numChunks; ++i){
		packArgs argsP = getIDParams(tracks, fileOpt, i, numlines);
		if(DEBUG > 1)
			printf("host:%s, port:%d\n", argsP.hostname, argsP.port);

		getPackets(argsP.hostname, argsP.port);
	}

	return 0;
}
示例#14
0
文件: allegro.c 项目: gsrr/Python
void gettermoptions()
{
	struct option *o = getoptions("term");
	for (; o; o = o->next) {
		if (!strcmp(opt_key(o), "drawing")) {
			if (o->val.integ)
				textgfx_flags |= ASCII;
		} else if (!strcmp(opt_key(o), "color")) {
			if (!o->val.integ)
				textgfx_flags |= MONOCHROME;
		} else
			blockstyle_from_option(o);
	}
	reset_block_chars();
}
示例#15
0
文件: logctl.c 项目: FrogyYen/rsyslog
int main (int argc, char *argv[])
{
	
	struct queryopt opt;
	struct ofields *fields;
	struct select_doc *s_doc;
	struct query_doc *qu_doc;
	struct db_connect *db_conn;
	struct output *out;
	struct db_cursor *db_c;
	struct results *res;

	opt.e_skip = 0;	  	  // standard
	opt.e_ret = 0;	  	  // standard
	opt.bsever  = 0;
        opt.blevel = 0;
	opt.bdate = 0;
	opt.bdateu = 0;
	opt.bdatef = 0;
	opt.bmsg = 0;
	opt.bskip = 0;
	opt.bsys = 0;
	
	getoptions(argc, argv, &opt);
	qu_doc = create_query(&opt);				// crate query
	s_doc = create_select();
	db_conn = create_conn();				// create connection
	out = launch_query(&opt, s_doc, qu_doc, db_conn);	// launch the query 
	db_c = open_cursor(db_conn, out);			// open cursor
	
	while (cursor_next(db_c))
	{
		res = read_data(db_c);
		fields = get_data(res);
        	formater(fields);				// formate output
		free(fields);
		free(res);
    	}

	free_cursor(db_c);
	close_conn(db_conn); 
	free(out);
	free(s_doc);
	free(qu_doc);
 
	return (0);
}
示例#16
0
int
main (int argc, char *argv[])
{
  int rt;

  rt = _i18n_init (I18N_CAT_MIN);

  setdefaults ();
  getoptions (argc, argv);
  getpids (argc, argv);
  printheader ();
  initstats ();
  processlogfile ();
  printsummary ();

  _i18n_end (ls_catd);
  return (0);

}
示例#17
0
void doinit()
{ /* initializes variables */

  inputnumbers(&spp, &loci, &nonodes2, 1);
  getoptions();
  if(!usertree)
    nonodes2--;
  if (printdata)
    fprintf(outfile, "\n%4ld Populations, %4ld Loci\n", spp, loci);
  alloctree(&curtree.nodep, nonodes2);
  if (!usertree) {
    alloctree(&bestree.nodep, nonodes2);
    alloctree(&priortree.nodep, nonodes2);
    if (njumble > 1) {
      alloctree(&bestree2.nodep, nonodes2);
    }
  }
  allocrest();
}  /* doinit */
示例#18
0
void doinput(int argc, Char *argv[])
{ /* reads the input data */
  getoptions();
  seqboot_inputnumbers();
  allocrest();
  if (weights)
    openfile(&weightfile,WEIGHTFILE,"input weight file",
               "r",argv[0],weightfilename);
  if (mixture){
    openfile(&mixfile,MIXFILE,"mixture file", "r",argv[0],mixfilename);
    openfile(&outmixfile,"outmixture","output mixtures file","w",argv[0],
               outmixfilename);
    seqboot_inputaux(mixdata, mixfile);
  }
  if (ancvar){
    openfile(&ancfile,ANCFILE,"ancestor file", "r",argv[0],ancfilename);
    openfile(&outancfile,"outancestors","output ancestors file","w",argv[0],
               outancfilename);
    seqboot_inputaux(ancdata, ancfile);
  }
  if (categories) {
    openfile(&catfile,CATFILE,"input category file","r",argv[0],catfilename);
    openfile(&outcatfile,"outcategories","output category file","w",argv[0],
               outcatfilename);
    inputcategs(0, sites, category, 9, "SeqBoot");
  }
  if (factors){
    openfile(&factfile,FACTFILE,"factors file","r",argv[0],factfilename);
    openfile(&outfactfile,"outfactors","output factors file","w",argv[0],
               outfactfilename);
  }
  if (justwts && !permute)
    openfile(&outweightfile,"outweights","output weight file",
               "w",argv[0],outweightfilename);
  else {
    openfile(&outfile,OUTFILE,"output data file","w",argv[0],outfilename);
  }
  inputoptions();
  seqboot_inputdata();
}  /* doinput */
示例#19
0
void doinput()
{
  /* reads the input data */

  inputnumbers(&spp, &chars, &nonodes, 1);
  words = chars / bits + 1;
  printf("%2ld species, %3ld characters\n", spp, chars);
  printf("\nReading input file ...\n\n");
  getoptions();
  if (weights)
      openfile(&weightfile,WEIGHTFILE,"weights file","r",progname,weightfilename);
  if(ancvar)
      openfile(&ancfile,ANCFILE,"ancestors file", "r",progname,ancfilename);
  if(factors)
      openfile(&factfile,FACTFILE,"factors file", "r",progname,factfilename);

  alloctree(&treenode);
  setuptree(treenode);
  allocrest();
  inputoptions();
  inputdata(treenode, dollo, false, stdout);
}  /* doinput */
示例#20
0
int main(int argc, char* argv[])
{
  try
  {

    struct t_hostparams params;
    getoptions(argc, argv, params);

	// Check command line arguments.
    if (params.notconfigured())
    {
      std::cerr << " To run final usage:  -h <address> -p <port> -d <doc_root>\n";
      std::cerr << " try:\n";
      std::cerr << " ./final -h 0.0.0.0 -p 80 -d .\n";
      return 1;
    }

   auto pid = fork();
   if (!pid)
   {
    httpservice::server myserver(params.host, params.port, params.doc_root);
    myserver.run();
   }
  else
  {
    std::ofstream f("final.pid");
    f << pid << std::endl;
  }

  }
  catch (std::exception& e)
  {
    std::cerr << "std::exception: " << e.what() << "\n";
  }

  return 0;
}
示例#21
0
static int
checkfs(const char *vfstype, const char *spec, const char *mntpt, void *auxarg,
    pid_t *pidp)
{
	/* List of directories containing fsck_xxx subcommands. */
	static const char *edirs[] = {
		_PATH_SBIN,
		_PATH_USRSBIN,
		NULL
	};
	const char **argv, **edir;
	pid_t pid;
	int argc, i, status, maxargc;
	char *optbuf = NULL, fsname[MAXPATHLEN], execname[MAXPATHLEN];
	const char *extra = getoptions(vfstype);

	if (strcmp(vfstype, "ufs") == 0)
		vfstype = MOUNT_UFS;

	maxargc = 100;
	argv = emalloc(sizeof(char *) * maxargc);

	argc = 0;
	(void)snprintf(fsname, sizeof(fsname), "fsck_%s", vfstype);
	argv[argc++] = fsname;

	if (options) {
		if (extra != NULL)
			optbuf = catopt(options, extra, 0);
		else
			optbuf = estrdup(options);
	}
	else if (extra)
		optbuf = estrdup(extra);

	if (optbuf)
		mangle(optbuf, &argc, &argv, &maxargc);

	argv[argc++] = spec;
	argv[argc] = NULL;

	if (flags & (CHECK_DEBUG|CHECK_VERBOSE)) {
		(void)printf("start %s %swait %s", mntpt,
			pidp ? "no" : "", fsname);
		for (i = 1; i < argc; i++)
			(void)printf(" %s", argv[i]);
		(void)printf("\n");
	}

	switch (pid = fork()) {
	case -1:				/* Error. */
		warn("fork");
		if (optbuf)
			free(optbuf);
		free(argv);
		return (1);

	case 0:					/* Child. */
		if (flags & CHECK_DEBUG)
			_exit(0);

		/* Go find an executable. */
		edir = edirs;
		do {
			(void)snprintf(execname,
			    sizeof(execname), "%s/fsck_%s", *edir, vfstype);
			execv(execname, (char * const *)argv);
			if (errno != ENOENT) {
				if (spec)
					warn("exec %s for %s", execname, spec);
				else
					warn("exec %s", execname);
			}
		} while (*++edir != NULL);

		if (errno == ENOENT) {
			if (spec)
				warn("exec %s for %s", execname, spec);
			else
				warn("exec %s", execname);
		}
		exit(1);
		/* NOTREACHED */

	default:				/* Parent. */
		if (optbuf)
			free(optbuf);
		free(argv);

		if (pidp) {
			*pidp = pid;
			return 0;
		}

		if (waitpid(pid, &status, 0) < 0) {
			warn("waitpid");
			return (1);
		}

		if (WIFEXITED(status)) {
			if (WEXITSTATUS(status) != 0)
				return (WEXITSTATUS(status));
		}
		else if (WIFSIGNALED(status)) {
			warnx("%s: %s", spec, strsignal(WTERMSIG(status)));
			return (1);
		}
		break;
	}

	return (0);
}
示例#22
0
文件: jam.c 项目: PPNav/GPSTk
int
main( int argc, char **argv, char **arg_environ )
{
	int		n, num_targets;
	const char	*s;
	struct option	optv[N_OPTS];
	char*       targets[N_TARGETS];
	const char	*all = "all";
	int		anyhow = 0;
	int		status;

# ifdef OS_MAC
	InitGraf(&qd.thePort);
# endif

	argc--, argv++;

	if( ( num_targets = getoptions( argc, argv, "d:j:f:gs:t:ano:qv", optv, targets ) ) < 0 )
	{
	    printf( "\nusage: jam [ options ] targets...\n\n" );

            printf( "-a      Build all targets, even if they are current.\n" );
            printf( "-dx     Display (a)actions (c)causes (d)dependencies\n" );
	    printf( "        (m)make tree (x)commands (0-9) debug levels.\n" );
            printf( "-fx     Read x instead of Jambase.\n" );
	    printf( "-g      Build from newest sources first.\n" );
            printf( "-jx     Run up to x shell commands concurrently.\n" );
            printf( "-n      Don't actually execute the updating actions.\n" );
            printf( "-ox     Write the updating actions to file x.\n" );
            printf( "-q      Quit quickly as soon as a target fails.\n" );
	    printf( "-sx=y   Set variable x=y, overriding environment.\n" );
            printf( "-tx     Rebuild x, even if it is up-to-date.\n" );
            printf( "-v      Print the version of jam and exit.\n\n" );

	    exit( EXITBAD );
	}

	/* Version info. */

	if( ( s = getoptval( optv, 'v', 0 ) ) )
	{
	    printf( "FT-Jam %s. %s. ", VERSION, OSMINOR );
	    printf( "(C) 1993-2003 Christopher Seiwald, see www.freetype.org/jam/\n" );

	    return EXITOK;
	}

	/* Pick up interesting options */

	if( ( s = getoptval( optv, 'n', 0 ) ) )
	    globs.noexec++, DEBUG_MAKE = DEBUG_MAKEQ = DEBUG_EXEC = 1; 

	if( ( s = getoptval( optv, 'q', 0 ) ) )
	    globs.quitquick = 1;

	if( ( s = getoptval( optv, 'a', 0 ) ) )
	    anyhow++;

	if( ( s = getoptval( optv, 'j', 0 ) ) )
	    globs.jobs = atoi( s );

	if( ( s = getoptval( optv, 'g', 0 ) ) )
	    globs.newestfirst = 1;

	/* Turn on/off debugging */

	for( n = 0; (s = getoptval( optv, 'd', n )) != 0; n++ )
	{
	    int i = atoi( s );

	    /* First -d, turn off defaults. */

	    if( !n )
		DEBUG_MAKE = DEBUG_MAKEQ = DEBUG_EXEC = 0;

	    /* n turns on levels 1-n */
	    /* +n turns on level n */
	    /* c turns on named display c */

	    if( i < 0 || i >= DEBUG_MAX )
	    {
		printf( "Invalid debug level '%s'.\n", s );
	    }
	    else if( *s == '+' )
	    {
		globs.debug[i] = 1;
	    }
	    else if( i ) while( i )
	    {
		globs.debug[i--] = 1;
	}
	    else while( *s ) switch( *s++ )
	    {
	    case 'a': DEBUG_MAKE = DEBUG_MAKEQ = 1; break;
	    case 'c': DEBUG_CAUSES = 1; break;
	    case 'd': DEBUG_DEPENDS = 1; break;
	    case 'm': DEBUG_MAKEPROG = 1; break;
	    case 'x': DEBUG_EXEC = 1; break;
	    case '0': break;
	    default: printf( "Invalid debug flag '%c'.\n", s[-1] );
	    }
	}

	/* Set JAMDATE first */

	{
	    char buf[ 128 ];
	    time_t clock;
	    time( &clock );
	    strcpy( buf, ctime( &clock ) );

	    /* Trim newline from date */

	    if( strlen( buf ) == 25 )
		buf[ 24 ] = 0;

	    var_set( "JAMDATE", list_new( L0, buf, 0 ), VAR_SET );
	}

	/* And JAMUNAME */
# ifdef unix
	{
	    struct utsname u;

	    if( uname( &u ) >= 0 )
	    {
		LIST *l = L0;
		l = list_new( l, u.machine, 0 );
		l = list_new( l, u.version, 0 );
		l = list_new( l, u.release, 0 );
		l = list_new( l, u.nodename, 0 );
		l = list_new( l, u.sysname, 0 );
		var_set( "JAMUNAME", l, VAR_SET );
	    }
	}
# endif /* unix */

	/*
	 * Jam defined variables OS, OSPLAT
	 */

	var_defines( othersyms );

	/* load up environment variables */

	var_defines( (const char **)use_environ );

	/* Load up variables set on command line. */

	for( n = 0; (s = getoptval( optv, 's', n )) != 0; n++ )
	{
	    const char *symv[2];
	    symv[0] = s;
	    symv[1] = 0;
	    var_defines( symv );
	}

	/* Initialize built-in rules */

	load_builtins();

	/* Parse ruleset */

	for( n = 0; (s = getoptval( optv, 'f', n )) != 0; n++ )
	    parse_file( s );

	if( !n )
	    parse_file( "+" );

	status = yyanyerrors();

	/* Manually touch -t targets */

	for( n = 0; (s = getoptval( optv, 't', n )) != 0; n++ )
	    touchtarget( s );

	/* If an output file is specified, set globs.cmdout to that */

	if( (s = getoptval( optv, 'o', 0 )) != 0 )
	{
	    if( !( globs.cmdout = fopen( s, "w" ) ) )
	    {
		printf( "Failed to write to '%s'\n", s );
		exit( EXITBAD );
	    }
	    globs.noexec++;
	}

    /* Add JAMCMDARGS
     */
     {
        LIST*  l = L0;

        for ( n = 0; n < num_targets; n++ )
          l = list_new( l, targets[n], 0 );

        var_set( "JAMCMDARGS", l, VAR_SET );
     }

	/* Now make target */

	if( !num_targets )
	    status |= make( 1, &all, anyhow );
	else
	    status |= make( num_targets, (const char**)targets, anyhow );

	/* Widely scattered cleanup */

	var_done();
	donerules();
	donestamps();
	donestr();

	/* close cmdout */

	if( globs.cmdout )
	    fclose( globs.cmdout );

	return status ? EXITBAD : EXITOK;
}
示例#23
0
static int
checkfs(const char *pvfstype, const char *spec, const char *mntpt,
    const char *auxopt, pid_t *pidp)
{
	const char ** volatile argv;
	pid_t pid;
	int argc, i, status, maxargc;
	char *optbuf, execbase[MAXPATHLEN];
	char *vfstype = NULL;
	const char *extra = NULL;

#ifdef __GNUC__
	/* Avoid vfork clobbering */
	(void) &optbuf;
	(void) &vfstype;
#endif
	/*
	 * We convert the vfstype to lowercase and any spaces to underscores
	 * to not confuse the issue
	 *
	 * XXX This is a kludge to make automatic filesystem type guessing
	 * from the disklabel work for "4.2BSD" filesystems.  It does a
	 * very limited subset of transliteration to a normalised form of
	 * filesystem name, and we do not seem to enforce a filesystem
	 * name character set.
	 */
	vfstype = strdup(pvfstype);
	if (vfstype == NULL)
		perr("strdup(pvfstype)");
	for (i = 0; i < (int)strlen(vfstype); i++) {
		vfstype[i] = tolower(vfstype[i]);
		if (vfstype[i] == ' ')
			vfstype[i] = '_';
	}

	extra = getoptions(vfstype);
	optbuf = NULL;
	if (options)
		catopt(&optbuf, options);
	if (extra)
		catopt(&optbuf, extra);
	if (auxopt)
		catopt(&optbuf, auxopt);
	else if (flags & DO_BACKGRD)
		catopt(&optbuf, "-B");

	maxargc = 64;
	argv = emalloc(sizeof(char *) * maxargc);

	(void) snprintf(execbase, sizeof(execbase), "fsck_%s", vfstype);
	argc = 0;
	argv[argc++] = execbase;
	if (optbuf)
		mangle(optbuf, &argc, &argv, &maxargc);
	argv[argc++] = spec;
	argv[argc] = NULL;

	if (flags & (CHECK_DEBUG|CHECK_VERBOSE)) {
		(void)printf("start %s %swait", mntpt, 
			pidp ? "no" : "");
		for (i = 0; i < argc; i++)
			(void)printf(" %s", argv[i]);
		(void)printf("\n");
	}

	switch (pid = vfork()) {
	case -1:				/* Error. */
		warn("vfork");
		if (optbuf)
			free(optbuf);
		free(vfstype);
		return (1);

	case 0:					/* Child. */
		if ((flags & CHECK_DEBUG) && auxopt == NULL)
			_exit(0);

		/* Go find an executable. */
		execvP(execbase, _PATH_SYSPATH, __DECONST(char * const *, argv));
		if (spec)
			warn("exec %s for %s in %s", execbase, spec, _PATH_SYSPATH);
		else
			warn("exec %s in %s", execbase, _PATH_SYSPATH);
		_exit(1);
		/* NOTREACHED */

	default:				/* Parent. */
		if (optbuf)
			free(optbuf);

		free(vfstype);

		if (pidp) {
			*pidp = pid;
			return 0;
		}

		if (waitpid(pid, &status, 0) < 0) {
			warn("waitpid");
			return (1);
		}

		if (WIFEXITED(status)) {
			if (WEXITSTATUS(status) != 0)
				return (WEXITSTATUS(status));
		}
		else if (WIFSIGNALED(status)) {
			warnx("%s: %s", spec, strsignal(WTERMSIG(status)));
			return (1);
		}
		break;
	}

	return (0);
}
示例#24
0
文件: jam.c 项目: nishiken/boost-svn
int main( int argc, char * * argv, char * * arg_environ )
{
    int                     n;
    char                  * s;
    struct bjam_option      optv[N_OPTS];
    char            const * all = "all";
    int                     status;
    int                     arg_c = argc;
    char          *       * arg_v = argv;
    char            const * progname = argv[0];
    module_t              * environ_module;

#if defined(unix) || defined(__unix)
    sigset_t sigmask;
    struct sigaction sa;

    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &sigmask, NULL);
    sa.sa_flags = 0;
    sa.sa_handler = child_sig_handler;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGCHLD, &sa, NULL);
    sigemptyset(&empty_sigmask);
#endif

    saved_argv0 = argv[0];

    BJAM_MEM_INIT();

# ifdef OS_MAC
    InitGraf(&qd.thePort);
# endif

    --argc;
    ++argv;

    if ( getoptions( argc, argv, "-:l:m:d:j:p:f:gs:t:ano:qv", optv ) < 0 )
    {
        printf( "\nusage: %s [ options ] targets...\n\n", progname );

        printf( "-a      Build all targets, even if they are current.\n" );
        printf( "-dx     Set the debug level to x (0-9).\n" );
        printf( "-fx     Read x instead of Jambase.\n" );
        /* printf( "-g      Build from newest sources first.\n" ); */
        printf( "-jx     Run up to x shell commands concurrently.\n" );
        printf( "-lx     Limit actions to x number of seconds after which they are stopped.\n" );
        printf( "-mx     Limit action output buffer to x kb's of data, after which action output is read and ignored.\n" );
        printf( "-n      Don't actually execute the updating actions.\n" );
        printf( "-ox     Write the updating actions to file x.\n" );
        printf( "-px     x=0, pipes action stdout and stderr merged into action output.\n" );
        printf( "-q      Quit quickly as soon as a target fails.\n" );
        printf( "-sx=y   Set variable x=y, overriding environment.\n" );
        printf( "-tx     Rebuild x, even if it is up-to-date.\n" );
        printf( "-v      Print the version of jam and exit.\n" );
        printf( "--x     Option is ignored.\n\n" );

        exit( EXITBAD );
    }

    /* Version info. */
    if ( ( s = getoptval( optv, 'v', 0 ) ) )
    {
        printf( "Boost.Jam  " );
        printf( "Version %s. %s.\n", VERSION, OSMINOR );
        printf( "   Copyright 1993-2002 Christopher Seiwald and Perforce Software, Inc.  \n" );
        printf( "   Copyright 2001 David Turner.\n" );
        printf( "   Copyright 2001-2004 David Abrahams.\n" );
        printf( "   Copyright 2002-2008 Rene Rivera.\n" );
        printf( "   Copyright 2003-2008 Vladimir Prus.\n" );

        return EXITOK;
    }

    /* Pick up interesting options. */
    if ( ( s = getoptval( optv, 'n', 0 ) ) )
        globs.noexec++, globs.debug[2] = 1;

    if ( ( s = getoptval( optv, 'p', 0 ) ) )
    {
        /* Undocumented -p3 (acts like both -p1 -p2) means separate pipe action
         * stdout and stderr.
         */
        globs.pipe_action = atoi( s );
        if ( ( 3 < globs.pipe_action ) || ( globs.pipe_action < 0 ) )
        {
            printf(
                "Invalid pipe descriptor '%d', valid values are -p[0..3].\n",
                globs.pipe_action );
            exit( EXITBAD );
        }
    }

    if ( ( s = getoptval( optv, 'q', 0 ) ) )
        globs.quitquick = 1;

    if ( ( s = getoptval( optv, 'a', 0 ) ) )
        anyhow++;

    if ( ( s = getoptval( optv, 'j', 0 ) ) )
    {
        globs.jobs = atoi( s );
        if (globs.jobs == 0)
        {
            printf("Invalid value for the '-j' option.\n");
            exit(EXITBAD);
        }
    }

    if ( ( s = getoptval( optv, 'g', 0 ) ) )
        globs.newestfirst = 1;

    if ( ( s = getoptval( optv, 'l', 0 ) ) )
        globs.timeout = atoi( s );

    if ( ( s = getoptval( optv, 'm', 0 ) ) )
        globs.maxbuf = atoi( s ) * 1024;

    /* Turn on/off debugging */
    for ( n = 0; ( s = getoptval( optv, 'd', n ) ); ++n )
    {
        int i;

        /* First -d, turn off defaults. */
        if ( !n )
            for ( i = 0; i < DEBUG_MAX; ++i )
                globs.debug[i] = 0;

        i = atoi( s );

        if ( ( i < 0 ) || ( i >= DEBUG_MAX ) )
        {
            printf( "Invalid debug level '%s'.\n", s );
            continue;
        }

        /* n turns on levels 1-n. */
        /* +n turns on level n. */
        if ( *s == '+' )
            globs.debug[i] = 1;
        else while ( i )
            globs.debug[i--] = 1;
    }

    constants_init();

    {
        PROFILE_ENTER( MAIN );

#ifdef HAVE_PYTHON
        {
            PROFILE_ENTER( MAIN_PYTHON );
            Py_Initialize();
            {
                static PyMethodDef BjamMethods[] = {
                    {"call", bjam_call, METH_VARARGS,
                     "Call the specified bjam rule."},
                    {"import_rule", bjam_import_rule, METH_VARARGS,
                     "Imports Python callable to bjam."},
                    {"define_action", bjam_define_action, METH_VARARGS,
                     "Defines a command line action."},
                    {"variable", bjam_variable, METH_VARARGS,
                     "Obtains a variable from bjam's global module."},
                    {"backtrace", bjam_backtrace, METH_VARARGS,
                     "Returns bjam backtrace from the last call into Python."},
                    {"caller", bjam_caller, METH_VARARGS,
                     "Returns the module from which the last call into Python is made."},
                    {NULL, NULL, 0, NULL}
                };

                Py_InitModule( "bjam", BjamMethods );
            }
            PROFILE_EXIT( MAIN_PYTHON );
        }
#endif

#ifndef NDEBUG
        run_unit_tests();
#endif
#if YYDEBUG != 0
        if ( DEBUG_PARSE )
            yydebug = 1;
#endif

        /* Set JAMDATE. */
        var_set( root_module(), constant_JAMDATE, list_new( L0, outf_time(time(0)) ), VAR_SET );

        /* Set JAM_VERSION. */
        var_set( root_module(), constant_JAM_VERSION,
                 list_new( list_new( list_new( L0,
                   object_new( VERSION_MAJOR_SYM ) ),
                   object_new( VERSION_MINOR_SYM ) ),
                   object_new( VERSION_PATCH_SYM ) ),
                   VAR_SET );

        /* Set JAMUNAME. */
#if defined(unix) || defined(__unix)
        {
            struct utsname u;

            if ( uname( &u ) >= 0 )
            {
                var_set( root_module(), constant_JAMUNAME,
                         list_new(
                             list_new(
                                 list_new(
                                     list_new(
                                         list_new( L0,
                                            object_new( u.sysname ) ),
                                         object_new( u.nodename ) ),
                                     object_new( u.release ) ),
                                 object_new( u.version ) ),
                             object_new( u.machine ) ), VAR_SET );
            }
        }
#endif /* unix */

        /* Load up environment variables. */

        /* First into the global module, with splitting, for backward
         * compatibility.
         */
        var_defines( root_module(), use_environ, 1 );

        environ_module = bindmodule( constant_ENVIRON );
        /* Then into .ENVIRON, without splitting. */
        var_defines( environ_module, use_environ, 0 );

        /*
         * Jam defined variables OS & OSPLAT. We load them after environment, so
         * that setting OS in environment does not change Jam's notion of the
         * current platform.
         */
        var_defines( root_module(), othersyms, 1 );

        /* Load up variables set on command line. */
        for ( n = 0; ( s = getoptval( optv, 's', n ) ); ++n )
        {
            char *symv[2];
            symv[ 0 ] = s;
            symv[ 1 ] = 0;
            var_defines( root_module(), symv, 1 );
            var_defines( environ_module, symv, 0 );
        }

        /* Set the ARGV to reflect the complete list of arguments of invocation.
         */
        for ( n = 0; n < arg_c; ++n )
        {
            var_set( root_module(), constant_ARGV, list_new( L0, object_new( arg_v[n] ) ), VAR_APPEND );
        }

        /* Initialize built-in rules. */
        load_builtins();

        /* Add the targets in the command line to the update list. */
        for ( n = 1; n < arg_c; ++n )
        {
            if ( arg_v[ n ][ 0 ] == '-' )
            {
                char * f = "-:l:d:j:f:gs:t:ano:qv";
                for ( ; *f; ++f ) if ( *f == arg_v[ n ][ 1 ] ) break;
                if ( ( f[ 1 ] == ':' ) && ( arg_v[ n ][ 2 ] == '\0' ) ) ++n;
            }
            else
            {
                OBJECT * target = object_new( arg_v[ n ] );
                mark_target_for_updating( target );
                object_free( target );
            }
        }

        if (!targets_to_update())
        {
            mark_target_for_updating( constant_all );
        }

        /* Parse ruleset. */
        {
            FRAME frame[ 1 ];
            frame_init( frame );
            for ( n = 0; ( s = getoptval( optv, 'f', n ) ); ++n )
            {
                OBJECT * filename = object_new( s );
                parse_file( filename, frame );
                object_free( filename );
            }

            if ( !n )
            {
                parse_file( constant_plus, frame );
            }
        }

        status = yyanyerrors();

        /* Manually touch -t targets. */
        for ( n = 0; ( s = getoptval( optv, 't', n ) ); ++n )
        {
            OBJECT * target = object_new( s );
            touch_target( target );
            object_free( target );
        }

        /* If an output file is specified, set globs.cmdout to that. */
        if ( ( s = getoptval( optv, 'o', 0 ) ) )
        {
            if ( !( globs.cmdout = fopen( s, "w" ) ) )
            {
                printf( "Failed to write to '%s'\n", s );
                exit( EXITBAD );
            }
            ++globs.noexec;
        }

        /* The build system may set the PARALLELISM variable to override -j
           options.  */
        {
            LIST *p = L0;
            p = var_get ( root_module(), constant_PARALLELISM );
            if ( p )
            {
                int j = atoi( object_str( p->value ) );
                if ( j == -1 )
                {
                    printf( "Invalid value of PARALLELISM: %s\n", object_str( p->value ) );
                }
                else
                {
                    globs.jobs = j;
                }
            }
        }

        /* KEEP_GOING overrides -q option. */
        {
            LIST *p = L0;
            p = var_get( root_module(), constant_KEEP_GOING );
            if ( p )
            {
                int v = atoi( object_str( p->value ) );
                if ( v == 0 )
                    globs.quitquick = 1;
                else
                    globs.quitquick = 0;
            }
        }

        /* Now make target. */
        {
            PROFILE_ENTER( MAIN_MAKE );

            LIST * targets = targets_to_update();
            if (targets)
            {
                int targets_count = list_length( targets );
                OBJECT * * targets2 = (OBJECT * *)
                    BJAM_MALLOC( targets_count * sizeof( OBJECT * ) );
                int n = 0;
                for ( ; targets; targets = list_next( targets ) )
                    targets2[ n++ ] = targets->value;
                status |= make( targets_count, targets2, anyhow );
                BJAM_FREE( (void *)targets2 );
            }
            else
            {
                status = last_update_now_status;
            }

            PROFILE_EXIT( MAIN_MAKE );
        }

        PROFILE_EXIT( MAIN );
    }

    if ( DEBUG_PROFILE )
        profile_dump();

    
#ifdef OPT_HEADER_CACHE_EXT
    hcache_done();
#endif

    clear_targets_to_update();

    /* Widely scattered cleanup. */
    file_done();
    rules_done();
    stamps_done();
    search_done();
    class_done();
    modules_done();
    regex_done();
    exec_done();
    pwd_done();
    path_done();
    function_done();
    list_done();
    constants_done();
    object_done();

    /* Close cmdout. */
    if ( globs.cmdout )
        fclose( globs.cmdout );

#ifdef HAVE_PYTHON
    Py_Finalize();
#endif

    BJAM_MEM_CLOSE();

    return status ? EXITBAD : EXITOK;
}
示例#25
0
文件: idlestat.c 项目: bigzz/idlestat
int main(int argc, char *argv[], char *const envp[])
{
	struct cpuidle_datas *datas;
	struct cpuidle_datas *baseline;
	struct program_options options;
	int args;
	double start_ts = 0, end_ts = 0;
	struct init_pstates *initp = NULL;
	struct report_ops *output_handler = NULL;
	struct cpu_topology *cpu_topo = NULL;
	struct trace_options *saved_trace_options = NULL;
	void *report_data = NULL;

	args = getoptions(argc, argv, &options);
	if (args <= 0)
		return 1;

	/* Tracing requires manipulation of some files only accessible
	 * to root */
	if ((options.mode == TRACE) && getuid()) {
		fprintf(stderr, "must be root to run traces\n");
		return 1;
	}

	output_handler = get_report_ops(options.report_type_name);
	if (is_err(output_handler))
		return 1;

	if (output_handler->check_options &&
			output_handler->check_options(&options) < 0)
		return 1;

	if (output_handler->allocate_report_data) {
		report_data = output_handler->allocate_report_data(&options);
		if (is_err(report_data))
			return 1;
	}

	if (output_handler->check_output(&options, report_data))
		return 1;

	if (options.energy_model_filename &&
		parse_energy_model(&options) < 0) {
		fprintf(stderr, "can't parse energy model file\n");
		return 1;
	}

	/* Acquisition time specified means we will get the traces */
	if ((options.mode == TRACE) || args < argc) {
		/* Read cpu topology info from sysfs */
		cpu_topo = read_sysfs_cpu_topo();
		if (is_err(cpu_topo)) {
			fprintf(stderr, "Failed to read CPU topology info from"
				" sysfs.\n");
			return 1;
		}

		/* Stop tracing (just in case) */
		if (idlestat_trace_enable(false)) {
			fprintf(stderr, "idlestat requires kernel Ftrace and "
				"debugfs mounted on /sys/kernel/debug\n");
			return 1;
		}

		saved_trace_options = idlestat_store_trace_options();
		if (is_err(saved_trace_options))
			return 1;

		/*
		 * Calculate/verify buffer size and polling trace data
		 * interval. The interval or may may not be used to
		 * transfer data from kernel trace buffer to some
		 * storage media. It is needed for long eventful traces,
		 * but is not preferred. If the user does not specify
		 * the values, we will calculate reasonable defaults.
		 */
		if (calculate_buffer_parameters(options.duration, &options.tbs))
			return 1;

		/* Initialize the traces for cpu_idle and increase the
		 * buffer size to let 'idlestat' to possibly sleep instead
		 * of acquiring data, hence preventing it to pertubate the
		 * measurements. */
		if (idlestat_init_trace(options.tbs.percpu_buffer_size))
			goto err_restore_trace_options;

		/* Remove all the previous traces */
		if (idlestat_flush_trace())
			goto err_restore_trace_options;

		/* Get starting timestamp */
		if (get_trace_ts(&start_ts) == -1)
			goto err_restore_trace_options;

		initp = build_init_pstates(cpu_topo);

		/* Start the recording */
		if (idlestat_trace_enable(true))
			goto err_restore_trace_options;

		/* We want to prevent to begin the acquisition with a cpu in
		 * idle state because we won't be able later to close the
		 * state and to determine which state it was. */
		if (idlestat_wake_all())
			goto err_restore_trace_options;

		/* Execute the command or wait a specified delay */
		if (execute(argc - args, &argv[args], envp, &options))
			goto err_restore_trace_options;

		/* Wake up all cpus again to account for last idle state */
		if (idlestat_wake_all())
			goto err_restore_trace_options;

		/* Stop tracing */
		if (idlestat_trace_enable(false))
			goto err_restore_trace_options;

		/* Get ending timestamp */
		if (get_trace_ts(&end_ts) == -1)
			goto err_restore_trace_options;

		/* At this point we should have some spurious wake up
		 * at the beginning of the traces and at the end (wake
		 * up all cpus and timer expiration for the timer
		 * acquisition). We assume these will be lost in the number
		 * of other traces and could be negligible. */
		if (idlestat_store(options.filename, start_ts, end_ts,
			initp, cpu_topo))
			goto err_restore_trace_options;

		/* Restore original kernel ftrace options */
		if (idlestat_restore_trace_options(saved_trace_options))
			return 1;

		/* Discard topology, will be reloaded during trace load */
		release_cpu_topo_cstates(cpu_topo);
		release_cpu_topo_info(cpu_topo);
		cpu_topo = NULL;
	}

	/* Load the idle states information */
	datas = idlestat_load(options.filename);

	if (is_err(datas))
		return 1;

	cpu_topo = datas->topo;

	if (options.baseline_filename) {
		baseline = idlestat_load(options.baseline_filename);
		merge_pstates(datas, baseline);
	} else {
		baseline = NULL;
	}

	if (is_err(baseline))
		return 1;

	datas->baseline = baseline;
	assign_baseline_in_topo(datas);

	if (output_handler->open_report_file(options.outfilename, report_data))
		return 1;

	if (options.display & IDLE_DISPLAY) {
		output_handler->cstate_table_header(report_data);
		dump_cpu_topo_info(output_handler, report_data,
				display_cstates, cpu_topo, 1);
		output_handler->cstate_table_footer(report_data);
	}

	if (options.display & FREQUENCY_DISPLAY) {
		output_handler->pstate_table_header(report_data);
		dump_cpu_topo_info(output_handler, report_data,
				display_pstates, cpu_topo, 0);
		output_handler->pstate_table_footer(report_data);
	}

	if (options.display & WAKEUP_DISPLAY) {
		output_handler->wakeup_table_header(report_data);
		dump_cpu_topo_info(output_handler, report_data,
				display_wakeup, cpu_topo, 1);
		output_handler->wakeup_table_footer(report_data);
	}

	if (options.energy_model_filename)
		calculate_energy_consumption(cpu_topo);

	output_handler->close_report_file(report_data);

	release_init_pstates(initp);
	release_datas(datas);

	if (output_handler->release_report_data)
		output_handler->release_report_data(report_data);

	return 0;

 err_restore_trace_options:
	/* Restore original kernel ftrace options */
	idlestat_restore_trace_options(saved_trace_options);
	return 1;
}
示例#26
0
文件: rez.cpp 项目: HaikuArchives/Pe
int main(int argc, char *argv[])
{
	yyin = stdin;

	int i = getoptions(argc, argv);

	char buf[PATH_MAX];
	if (out[0] == '/')
		strcpy(buf, out);
	else
	{
		getcwd(buf, PATH_MAX);
		strcat(buf, "/");
		strcat(buf, out);
	}

	BEntry e;
	if (e.SetTo(out)) error("entry set to %s", out);

	BDirectory d;
	if (e.GetParent(&d)) error("get parent of %s", out);
	if ((gTruncate || gSaveAsHeader) && e.Exists() && e.Remove())
		error("removing %s", out);

	BFile f;
	BResources res;

	if (!gDump)
	{
		if (gTruncate || !e.Exists())
		{
			if (d.CreateFile(buf, &f)) error("creating %s", buf);
			gTruncate = true;
		}
		else
			if (f.SetTo(buf, B_READ_WRITE)) error("opening %s", buf);

		if (gSaveAsHeader)
		{
			gHeader = fopen(buf, "w");
			if (!gHeader) error("Error creating %s", buf);
		}
		else if (res.SetTo(&f, gTruncate) != B_NO_ERROR)
			error("opening resource file %s", buf);
	}

	resFile = &res;

	if (i == argc)
		Work(NULL);
	else
	{
		while (i < argc)
			Work(in = argv[i++]);
	}

	if (verbose)
		puts("done");

	if (gHeader)
		fclose(gHeader);
	else
		f.Sync();

	return 0;
} /* main */
示例#27
0
/*
 * Search for variable, if not found create globally.
 */
struct tbl *
global(const char *n)
{
	struct block *l = e->loc;
	struct tbl *vp;
	int c;
	unsigned int h;
	bool	 array;
	int	 val;

	/* Check to see if this is an array */
	n = array_index_calc(n, &array, &val);
	h = hash(n);
	c = n[0];
	if (!letter(c)) {
		if (array)
			errorf("bad substitution");
		vp = &vtemp;
		vp->flag = DEFINED;
		vp->type = 0;
		vp->areap = ATEMP;
		*vp->name = c;
		if (digit(c)) {
			for (c = 0; digit(*n); n++)
				c = c*10 + *n-'0';
			if (c <= l->argc)
				/* setstr can't fail here */
				setstr(vp, l->argv[c], KSH_RETURN_ERROR);
			vp->flag |= RDONLY;
			return vp;
		}
		vp->flag |= RDONLY;
		if (n[1] != '\0')
			return vp;
		vp->flag |= ISSET|INTEGER;
		switch (c) {
		case '$':
			vp->val.i = kshpid;
			break;
		case '!':
			/* If no job, expand to nothing */
			if ((vp->val.i = j_async()) == 0)
				vp->flag &= ~(ISSET|INTEGER);
			break;
		case '?':
			vp->val.i = exstat;
			break;
		case '#':
			vp->val.i = l->argc;
			break;
		case '-':
			vp->flag &= ~INTEGER;
			vp->val.s = getoptions();
			break;
		default:
			vp->flag &= ~(ISSET|INTEGER);
		}
		return vp;
	}
	for (l = e->loc; ; l = l->next) {
		vp = ktsearch(&l->vars, n, h);
		if (vp != NULL) {
			if (array)
				return arraysearch(vp, val);
			else
				return vp;
		}
		if (l->next == NULL)
			break;
	}
	vp = ktenter(&l->vars, n, h);
	if (array)
		vp = arraysearch(vp, val);
	vp->flag |= DEFINED;
	if (special(n))
		vp->flag |= SPECIAL;
	return vp;
}
示例#28
0
static int
checkfs(const char *vfst, const char *spec, const char *mntpt, void *auxarg,
    pid_t *pidp)
{
	/* List of directories containing fsck_xxx subcommands. */
	static const char *edirs[] = {
#ifdef RESCUEDIR
		RESCUEDIR,
#endif
		_PATH_SBIN,
		_PATH_USRSBIN,
		NULL
	};
	const char ** volatile argv, **edir;
	const char * volatile vfstype = vfst;
	pid_t pid;
	int argc, i, status, maxargc;
	char *optb;
	char *volatile optbuf;
	char execname[MAXPATHLEN + 1], execbase[MAXPATHLEN];
	const char *extra = getoptions(vfstype);

	if (!strcmp(vfstype, "ufs"))
		vfstype = MOUNT_UFS;

	optb = NULL;
	if (options)
		catopt(&optb, options);
	if (extra)
		catopt(&optb, extra);
	optbuf = optb;

	maxargc = 64;
	argv = emalloc(sizeof(char *) * maxargc);

	(void) snprintf(execbase, sizeof(execbase), "fsck_%s", vfstype);
	argc = 0;
	argv[argc++] = execbase;
	if (optbuf)
		mangle(optbuf, &argc, &argv, &maxargc);
	argv[argc++] = spec;
	argv[argc] = NULL;

	if (flags & (CHECK_DEBUG|CHECK_VERBOSE)) {
		(void)printf("start %s %swait", mntpt, 
			pidp ? "no" : "");
		for (i = 0; i < argc; i++)
			(void)printf(" %s", argv[i]);
		(void)printf("\n");
	}

	switch (pid = vfork()) {
	case -1:				/* Error. */
		warn("vfork");
		if (optbuf)
			free(optbuf);
		free(argv);
		return FSCK_EXIT_CHECK_FAILED;

	case 0:					/* Child. */
		if ((flags & CHECK_FORCE) == 0) {
			struct statvfs	sfs;

				/*
				 * if mntpt is a mountpoint of a mounted file
				 * system and it's mounted read-write, skip it
				 * unless -f is given.
				 */
			if ((statvfs(mntpt, &sfs) == 0) &&
			    (strcmp(mntpt, sfs.f_mntonname) == 0) &&
			    ((sfs.f_flag & MNT_RDONLY) == 0)) {
				printf(
		"%s: file system is mounted read-write on %s; not checking\n",
				    spec, mntpt);
				if ((flags & CHECK_PREEN) && auxarg != NULL)
					_exit(FSCK_EXIT_OK);	/* fsck -p */
				else
					_exit(FSCK_EXIT_CHECK_FAILED);	/* fsck [[-p] ...] */
			}
		}

		if (flags & CHECK_DEBUG)
			_exit(FSCK_EXIT_OK);

		/* Go find an executable. */
		edir = edirs;
		do {
			(void)snprintf(execname,
			    sizeof(execname), "%s/%s", *edir, execbase);
			execv(execname, (char * const *)__UNCONST(argv));
			if (errno != ENOENT) {
				if (spec)
					warn("exec %s for %s", execname, spec);
				else
					warn("exec %s", execname);
			}
		} while (*++edir != NULL);

		if (errno == ENOENT) {
			if (spec)
				warn("exec %s for %s", execname, spec);
			else
				warn("exec %s", execname);
		}
		_exit(FSCK_EXIT_CHECK_FAILED);
		/* NOTREACHED */

	default:				/* Parent. */
		if (optbuf)
			free(optbuf);
		free(argv);

		if (pidp) {
			*pidp = pid;
			return FSCK_EXIT_OK;
		}

		if (waitpid(pid, &status, 0) < 0) {
			warn("waitpid");
			return FSCK_EXIT_CHECK_FAILED;
		}

		if (WIFEXITED(status)) {
			if (WEXITSTATUS(status) != 0)
				return WEXITSTATUS(status);
		}
		else if (WIFSIGNALED(status)) {
			warnx("%s: %s", spec, strsignal(WTERMSIG(status)));
			return FSCK_EXIT_CHECK_FAILED;
		}
		break;
	}

	return FSCK_EXIT_OK;
}
示例#29
0
文件: var.c 项目: rovaughn/distro
/*
 * Search for variable, if not found create globally.
 */
struct tbl *
global(const char *n)
{
	struct block *l = e->loc;
	struct tbl *vp;
	int c;
	bool array;
	uint32_t h, val;

	/*
	 * check to see if this is an array;
	 * dereference namerefs; must come first
	 */
	n = array_index_calc(n, &array, &val);
	h = hash(n);
	c = (unsigned char)n[0];
	if (!ksh_isalphx(c)) {
		if (array)
			errorf("bad substitution");
		vp = &vtemp;
		vp->flag = DEFINED;
		vp->type = 0;
		vp->areap = ATEMP;
		*vp->name = c;
		if (ksh_isdigit(c)) {
			if (getn(n, &c) && (c <= l->argc))
				/* setstr can't fail here */
				setstr(vp, l->argv[c], KSH_RETURN_ERROR);
			vp->flag |= RDONLY;
			return (vp);
		}
		vp->flag |= RDONLY;
		if (n[1] != '\0')
			return (vp);
		vp->flag |= ISSET|INTEGER;
		switch (c) {
		case '$':
			vp->val.i = kshpid;
			break;
		case '!':
			/* if no job, expand to nothing */
			if ((vp->val.i = j_async()) == 0)
				vp->flag &= ~(ISSET|INTEGER);
			break;
		case '?':
			vp->val.i = exstat & 0xFF;
			break;
		case '#':
			vp->val.i = l->argc;
			break;
		case '-':
			vp->flag &= ~INTEGER;
			vp->val.s = getoptions();
			break;
		default:
			vp->flag &= ~(ISSET|INTEGER);
		}
		return (vp);
	}
	l = varsearch(e->loc, &vp, n, h);
	if (vp != NULL)
		return (array ? arraysearch(vp, val) : vp);
	vp = ktenter(&l->vars, n, h);
	if (array)
		vp = arraysearch(vp, val);
	vp->flag |= DEFINED;
	if (special(n))
		vp->flag |= SPECIAL;
	return (vp);
}
示例#30
0
int main(int argc, char** argv)
{
  try {
    if (getoptions(argc, argv) != 0) 
      return 1;
    
    expgram::NGramCounts ngram(ngram_file, shards, debug);
    
    std::string  line;
    tokens_type  tokens;

    const int order = ngram.index.order();
    
    while (std::getline(std::cin, line)) {
      tokenizer_type tokenizer(line);
      
      // Here, we store in vector<string>.
      
      tokens.clear();
      tokens.insert(tokens.end(), tokenizer.begin(), tokenizer.end());
      
      
      //
      // Alternatively, you can try: (Remark: sentence is simply vector<word_type>)
      // 
      // sentence.clear();
      // sentence.insert(sentence.end(), tokenizer.begin(), tokenizer.end());
      //
      // and iterate over sentence type, not tokens.
      //
      
      //
      // The above example still automatically convert word_type into word_type::id_type on the fly.
      // An alternative faster approach is: (Remark: we assume id_set is vector<word_type::id_type> )
      //
      // id_set.clear();
      // for (tokenizer_type::iterator titer = tokenizer.begin(); titer != tokenizer.end(); ++ titer)
      //   id_set.push_back(ngram.index.vocab()[*titer]);
      //
      // then, you can iterate over id_set, not tokens.
      //
      
      // 
      // Note that the word_type will automatically assign id which may not
      // match with the word-id assigned by the indexed ngram language model.
      // This means that even OOV by the ngram language model may be assigned word-id.
      // If you want to avoid this, here is a solution:
      //
      // const word_type::id_type unk_id = ngram.index.vocab()[vocab_type::UNK]
      //
      // id_set.clear();
      // for (tokenizer_type::iterator titer = tokenizer.begin(); titer != tokenizer.end(); ++ titer)
      //   id_set.push_back(ngram.index.vocab().exists(*titer) ? ngram.index.vocab()[*titer] : unk_id);
      //

      // ngram access must use containser that supports forward-iterator concepts.
      // If not sure, use vector!

      std::copy(tokens.begin(), tokens.end(), std::ostream_iterator<std::string>(std::cout, " "));
      std::cout << ngram(tokens.begin(), tokens.end()) << std::endl;
    }
  }
  catch (std::exception& err) {
    std::cerr << "error: " << err.what() << std::endl;
    return 1;
  }
  return 0;
}