Beispiel #1
0
int main(int argc, char *argv[])
{
	int				pid;
	pthread_t		tcp_thread;
	char			*err_msg;

    /* parse cmdline arguments */
    parse_cmdline(argc, argv);

    /* initialize device communication */
    err_msg = NULL;
	if (aquaero_init(&err_msg) != 0) {
		log_msg(LOG_ERR, err_msg);
		exit(EXIT_FAILURE);
	}

    /* daemonize */
    if (opts.fork) {
    	pid = fork();
    	switch (pid) {
    		case -1:
				/* fork failure */
				log_msg(LOG_ERR, "failed to fork into background: %s",
						strerror(errno));
				exit(EXIT_FAILURE);
				break;
    		case 0:
    			/* child */
    			setsid();
    			log_msg(LOG_INFO, "started by user %d", getuid());
    			break;
    		default:
    			/* parent */
    			exit(EXIT_SUCCESS);
    			break;
    	}
    }

    /* write pid-file */
    if (opts.pidfile)
		if (write_pidfile(pid) != 0)
			log_msg(LOG_WARNING, "failed to write %s: %s", PID_FILE,
					strerror(errno));

    /* register signals */
    signal(SIGINT, signal_handler);
    signal(SIGHUP, signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGQUIT, signal_handler);

    /* setup data sync mutex */
    if (pthread_mutex_init(&data_lock, NULL) != 0)
    	err_die("failed to setup mutex, terminating");

    /* initial poll */
    if (poll_data() != 0)
    	die();

    /* start tcp server, spawn handler thread */
	if (tcp_start_server() != 0)
		err_die("error opening tcp server socket, terminating");
	if (pthread_create(&tcp_thread, NULL, tcp_handler, NULL) != 0)
		err_die("error spawning listen-thread, terminating");
	log_msg(LOG_INFO, "listening on port %d", opts.port);

	/* start infinite polling-loop */
	while (1) {
		if (poll_data() != 0)
			die();
		sleep(opts.interval);
	}

	return 0;
}
Beispiel #2
0
/* the main program... */
int main(int argc, char *argv[])
{
  int i;
  sigset_t signalmask, oldmask;
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
  struct timespec ts;
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
  /* close all file descriptors (except stdin/out/err) */
  daemonize_closefds();
  /* parse the command line */
  parse_cmdline(argc, argv);
  /* clean the environment */
#ifdef HAVE_CLEARENV
  if (clearenv() || putenv("HOME=/") || putenv("TMPDIR=/tmp") ||
      putenv("LDAPNOINIT=1"))
  {
    log_log(LOG_ERR, "clearing environment failed");
    exit(EXIT_FAILURE);
  }
#else /* not HAVE_CLEARENV */
  /* this is a bit ugly */
  environ = sane_environment;
#endif /* not HAVE_CLEARENV */
  /* disable the nss_ldap module for this process */
  disable_nss_ldap();
  /* set LDAP log level */
  if (myldap_set_debuglevel(nslcd_debugging) != LDAP_SUCCESS)
    exit(EXIT_FAILURE);
  /* read configuration file */
  cfg_init(NSLCD_CONF_PATH);
  /* set default mode for pidfile and socket */
  (void)umask((mode_t)0022);
  /* see if someone already locked the pidfile
     if --check option was given exit TRUE if daemon runs
     (pidfile locked), FALSE otherwise */
  if (nslcd_checkonly)
  {
    if (is_locked(NSLCD_PIDFILE))
    {
      log_log(LOG_DEBUG, "pidfile (%s) is locked", NSLCD_PIDFILE);
      exit(EXIT_SUCCESS);
    }
    else
    {
      log_log(LOG_DEBUG, "pidfile (%s) is not locked", NSLCD_PIDFILE);
      exit(EXIT_FAILURE);
    }
  }
  /* change directory */
  if (chdir("/") != 0)
  {
    log_log(LOG_ERR, "chdir failed: %s", strerror(errno));
    exit(EXIT_FAILURE);
  }
  /* normal check for pidfile locked */
  if (is_locked(NSLCD_PIDFILE))
  {
    log_log(LOG_ERR, "nslcd may already be active, cannot acquire lock (%s): %s",
            NSLCD_PIDFILE, strerror(errno));
    exit(EXIT_FAILURE);
  }
  /* daemonize */
  if ((!nslcd_debugging) && (!nslcd_nofork))
  {
    if (daemonize_daemon() != 0)
    {
      log_log(LOG_ERR, "unable to daemonize: %s", strerror(errno));
      exit(EXIT_FAILURE);
    }
  }
  /* intilialize logging */
  if (!nslcd_debugging)
  {
    daemonize_redirect_stdio();
    log_startlogging();
  }
  /* write pidfile */
  create_pidfile(NSLCD_PIDFILE);
  /* log start */
  log_log(LOG_INFO, "version %s starting", VERSION);
  /* install handler to close stuff off on exit and log notice */
  if (atexit(exithandler))
  {
    log_log(LOG_ERR, "atexit() failed: %s", strerror(errno));
    daemonize_ready(EXIT_FAILURE, "atexit() failed\n");
    exit(EXIT_FAILURE);
  }
  /* create socket */
  nslcd_serversocket = create_socket(NSLCD_SOCKET);
  /* start subprocess to do invalidating if reconnect_invalidate is set */
  for (i = 0; i < LM_NONE; i++)
    if (nslcd_cfg->reconnect_invalidate[i])
      break;
  if (i < LM_NONE)
    invalidator_start();
  /* change nslcd group and supplemental groups */
  if ((nslcd_cfg->gid != NOGID) && (nslcd_cfg->uidname != NULL))
  {
#ifdef HAVE_INITGROUPS
    /* load supplementary groups */
    if (initgroups(nslcd_cfg->uidname, nslcd_cfg->gid) < 0)
      log_log(LOG_WARNING, "cannot initgroups(\"%s\",%d) (ignored): %s",
              nslcd_cfg->uidname, (int)nslcd_cfg->gid, strerror(errno));
    else
      log_log(LOG_DEBUG, "initgroups(\"%s\",%d) done",
              nslcd_cfg->uidname, (int)nslcd_cfg->gid);
#else /* not HAVE_INITGROUPS */
#ifdef HAVE_SETGROUPS
    /* just drop all supplemental groups */
    if (setgroups(0, NULL) < 0)
      log_log(LOG_WARNING, "cannot setgroups(0,NULL) (ignored): %s",
              strerror(errno));
    else
      log_log(LOG_DEBUG, "setgroups(0,NULL) done");
#else /* not HAVE_SETGROUPS */
    log_log(LOG_DEBUG, "neither initgroups() or setgroups() available");
#endif /* not HAVE_SETGROUPS */
#endif /* not HAVE_INITGROUPS */
  }
  /* change to nslcd gid */
  if (nslcd_cfg->gid != NOGID)
  {
    if (setgid(nslcd_cfg->gid) != 0)
    {
      log_log(LOG_ERR, "cannot setgid(%d): %s",
              (int)nslcd_cfg->gid, strerror(errno));
      daemonize_ready(EXIT_FAILURE, "cannot setgid()\n");
      exit(EXIT_FAILURE);
    }
    log_log(LOG_DEBUG, "setgid(%d) done", (int)nslcd_cfg->gid);
  }
  /* change to nslcd uid */
  if (nslcd_cfg->uid != NOUID)
  {
    if (setuid(nslcd_cfg->uid) != 0)
    {
      log_log(LOG_ERR, "cannot setuid(%d): %s",
              (int)nslcd_cfg->uid, strerror(errno));
      daemonize_ready(EXIT_FAILURE, "cannot setuid()\n");
      exit(EXIT_FAILURE);
    }
    log_log(LOG_DEBUG, "setuid(%d) done", (int)nslcd_cfg->uid);
  }
  /* block all these signals so our worker threads won't handle them */
  sigemptyset(&signalmask);
  sigaddset(&signalmask, SIGHUP);
  sigaddset(&signalmask, SIGINT);
  sigaddset(&signalmask, SIGQUIT);
  sigaddset(&signalmask, SIGABRT);
  sigaddset(&signalmask, SIGPIPE);
  sigaddset(&signalmask, SIGTERM);
  sigaddset(&signalmask, SIGUSR1);
  sigaddset(&signalmask, SIGUSR2);
  pthread_sigmask(SIG_BLOCK, &signalmask, &oldmask);
  /* start worker threads */
  log_log(LOG_INFO, "accepting connections");
  nslcd_threads = (pthread_t *)malloc(nslcd_cfg->threads * sizeof(pthread_t));
  if (nslcd_threads == NULL)
  {
    log_log(LOG_CRIT, "main(): malloc() failed to allocate memory");
    daemonize_ready(EXIT_FAILURE, "malloc() failed to allocate memory\n");
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nslcd_cfg->threads; i++)
  {
    if (pthread_create(&nslcd_threads[i], NULL, worker, NULL))
    {
      log_log(LOG_ERR, "unable to start worker thread %d: %s",
              i, strerror(errno));
      daemonize_ready(EXIT_FAILURE, "unable to start worker thread\n");
      exit(EXIT_FAILURE);
    }
  }
  pthread_sigmask(SIG_SETMASK, &oldmask, NULL);
  /* install signalhandlers for some signals */
  install_sighandler(SIGHUP, sig_handler);
  install_sighandler(SIGINT, sig_handler);
  install_sighandler(SIGQUIT, sig_handler);
  install_sighandler(SIGABRT, sig_handler);
  install_sighandler(SIGPIPE, SIG_IGN);
  install_sighandler(SIGTERM, sig_handler);
  install_sighandler(SIGUSR1, sig_handler);
  install_sighandler(SIGUSR2, SIG_IGN);
  /* signal the starting process to exit because we can provide services now */
  daemonize_ready(EXIT_SUCCESS, NULL);
  /* wait until we received a signal */
  while ((nslcd_receivedsignal == 0) || (nslcd_receivedsignal == SIGUSR1))
  {
    sleep(INT_MAX); /* sleep as long as we can or until we receive a signal */
    if (nslcd_receivedsignal == SIGUSR1)
    {
      log_log(LOG_INFO, "caught signal %s (%d), refresh retries",
              signame(nslcd_receivedsignal), nslcd_receivedsignal);
      myldap_immediate_reconnect();
      nslcd_receivedsignal = 0;
    }
  }
  /* print something about received signal */
  log_log(LOG_INFO, "caught signal %s (%d), shutting down",
          signame(nslcd_receivedsignal), nslcd_receivedsignal);
  /* cancel all running threads */
  for (i = 0; i < nslcd_cfg->threads; i++)
    if (pthread_cancel(nslcd_threads[i]))
      log_log(LOG_WARNING, "failed to stop thread %d (ignored): %s",
              i, strerror(errno));
  /* close server socket to trigger failures in threads waiting on accept() */
  close(nslcd_serversocket);
  nslcd_serversocket = -1;
  /* if we can, wait a few seconds for the threads to finish */
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
  ts.tv_sec = time(NULL) + 3;
  ts.tv_nsec = 0;
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
  for (i = 0; i < nslcd_cfg->threads; i++)
  {
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
    pthread_timedjoin_np(nslcd_threads[i], NULL, &ts);
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
    if (pthread_kill(nslcd_threads[i], 0) == 0)
      log_log(LOG_ERR, "thread %d is still running, shutting down anyway", i);
  }
  /* we're done */
  return EXIT_FAILURE;
}
Beispiel #3
0
int main(int argc, char **argv)
{
  bool ran;
  json_t *cmd;
  pthread_mutexattr_t mattr;

  pthread_mutexattr_init(&mattr);
  pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE);
  pthread_mutex_init(&w_client_lock, &mattr);
  pthread_mutexattr_destroy(&mattr);

  parse_cmdline(&argc, &argv);

  if (foreground) {
    run_service();
    return 0;
  }

  w_set_thread_name("cli");
  cmd = build_command(argc, argv);
  preprocess_command(cmd, output_pdu);

  ran = try_command(cmd, 0);
  if (!ran && should_start(errno)) {
    if (no_spawn) {
      if (!no_local) {
        ran = try_client_mode_command(cmd, !no_pretty);
      }
    } else {
#ifdef USE_GIMLI
      spawn_via_gimli();
#elif defined(__APPLE__)
      spawn_via_launchd();
#elif defined(_WIN32)
      spawn_win32();
#else
      daemonize();
#endif
      ran = try_command(cmd, 10);
    }
  }

  json_decref(cmd);

  if (ran) {
    return 0;
  }

  if (!no_spawn) {
    w_log(W_LOG_ERR, "unable to talk to your watchman on %s! (%s)\n",
        sock_name, strerror(errno));
#ifdef __APPLE__
    if (getenv("TMUX")) {
      w_log(W_LOG_ERR, "\n"
"You may be hitting a tmux related session issue.\n"
"An immediate workaround is to run:\n"
"\n"
"    watchman version\n"
"\n"
"just once, from *outside* your tmux session, to allow the launchd\n"
"registration to be setup.  Once done, you can continue to access\n"
"watchman from inside your tmux sessions as usual.\n"
"\n"
"Longer term, you may wish to install this tool:\n"
"\n"
"    https://github.com/ChrisJohnsen/tmux-MacOSX-pasteboard\n"
"\n"
"and configure tmux to use `reattach-to-user-namespace`\n"
"when it launches your shell.\n");
    }
#endif
  }
  return 1;
}
Beispiel #4
0
int main()
{
    /* Declare automatic variables. */

    size_t  cmdlen  = 0;
    char *  cmdline = NULL;
    int     retval;

    /* Display the banner. */

    print_banner();

    /* Display the usage information if the command line is empty. */

    cmdlen = _bgetcmd( NULL, 0 );
    if( cmdlen == 0 ) {
        print_usage();
        return( EXIT_FAILURE );
    }

    /* Include space for the terminating null character. */

    cmdlen++;

    /* Get the command line. */

    cmdline = malloc( cmdlen );
    if( cmdline == NULL ) {
        return( EXIT_FAILURE );
    }

    cmdlen = _bgetcmd( cmdline, cmdlen );

    /* Initialize the globals. */

    initialize_globals();
    res_initialize_globals();

    /* Initialize the statics, which should be globals in gendev. */

    cur_file = (file_info *) malloc( sizeof( file_info ) );
    cur_file->filebuf = (char * ) malloc( BUF_SIZE );
    cur_file->buflen = BUF_SIZE;
    cur_file->scanptr = NULL;
    cur_file->usedlen = 0;

    cur_token = (token *) malloc( sizeof( token ) );

    /* Parse the command line: allocates and sets tgt_path. */

    retval = parse_cmdline( cmdline );
    if( retval == FAILURE ) {
        free( cmdline );
        return( EXIT_FAILURE );
    }

    /* Free the memory held by cmdline and reset it. */

    free( cmdline );
    cmdline = NULL;

    /* Check all files in current directory. */

    retval = check_directory();

    /* Free the memory held by tgt_path and the statics. */

    free( tgt_path );
    tgt_path = NULL;
    free( cur_file->filebuf );
    cur_file->filebuf = NULL;
    free( cur_file );
    cur_file = NULL;
    free( cur_token );
    cur_token = NULL;

    /* Print the useage if the process failed. */

    if( retval == FAILURE ) {
      print_usage();
      return( EXIT_FAILURE );
    }
    
    return( EXIT_SUCCESS );
}
int main(int argc, char **argv)
{
	int i;
	int status;
	char *fip_filename;
	int do_pack = 0;

	/* Clear file list table. */
	memset(files, 0, sizeof(files));

	/* Initialise for getopt_long().
	 * Use image table as defined at top of file to get options.
	 * Add 'dump' option and end marker.
	 */
	static struct option long_options[(sizeof(toc_entry_lookup_list)/
					   sizeof(entry_lookup_list)) + 1];

	for (i = 0;
	     /* -1 because we dont want to process end marker in toc table */
	     i < sizeof(toc_entry_lookup_list)/sizeof(entry_lookup_list) - 1;
	     i++) {
		long_options[i].name = toc_entry_lookup_list[i].command_line_name;
		/* The only flag defined at the moment is for a FILENAME */
		long_options[i].has_arg = toc_entry_lookup_list[i].flags ? 1 : 0;
		long_options[i].flag = 0;
		long_options[i].val = 0;
	}

	/* Add '--dump' option */
	long_options[i].name = "dump";
	long_options[i].has_arg = 0;
	long_options[i].flag = 0;
	long_options[i].val = 0;

	/* Zero the last entry (required) */
	long_options[++i].name = 0;
	long_options[i].has_arg = 0;
	long_options[i].flag = 0;
	long_options[i].val = 0;

#ifdef DEBUG
	/* Print all supported options */
	for (i = 0; i < sizeof(long_options)/sizeof(struct option); i++) {
		printf("long opt (%d) : name = %s\n", i, long_options[i].name);
	}
#endif /* DEBUG */

	/* As the package may already exist and is to be updated we need to get
	 * the filename from the arguments and load from it.
	 * NOTE: As this is the first function to look at the program arguments
	 * it causes a failure if bad options were provided.
	 */
	fip_filename = get_filename(argc, argv, long_options);
	if (fip_filename == NULL) {
		print_usage();
		return 0;
	}

	/* Try to open the file and load it into memory */
	status = parse_fip(fip_filename);
	if (status != 0) {
		return status;
	}

	/* Work through provided program arguments and perform actions */
	status = parse_cmdline(argc, argv, long_options, &do_pack);
	if (status != 0) {
		return status;
	};

	/* Processed all command line options. Create/update the package if
	 * required.
	 */
	if (do_pack) {
		status = pack_images(fip_filename);
		if (status != 0) {
			printf("Failed to create package (status = %d).\n",
			       status);
		}
	}

	return status;
}
Beispiel #6
0
idx_t* gpmetis( int argc, char **argv )
/*************************************************************************/
/*! Let the game begin! */
/*************************************************************************/
//int main(int argc, char *argv[])
{
  idx_t i;
  char *curptr, *newptr;
  idx_t options[METIS_NOPTIONS];
  graph_t *graph;
  idx_t *part;
  idx_t objval;
  params_t *params;
  int status=0;

  gk_optind = 0;

  //printf( "argc: %d\n", argc );
  //printf( "gk_optind %d\n", gk_optind );
  fflush( stdout );

    for( i = 0; i < argc; i++ )
    {
        //printf( "%s*\n", argv[ i ] );
    }


  params = parse_cmdline(argc, argv);
  //printf( "gk_optind %d\n", gk_optind );
  //fflush( stdout );
  //return NULL;

  gk_startcputimer(params->iotimer);
  graph = ReadGraph(params);

  ReadTPwgts(params, graph->ncon);
  gk_stopcputimer(params->iotimer);

  /* Check if the graph is contiguous */
  if (params->contig && !IsConnected(graph, 0)) {
    printf("***The input graph is not contiguous.\n"
           "***The specified -contig option will be ignored.\n");
    params->contig = 0;
  }

  /* Get ubvec if supplied */
  if (params->ubvecstr) {
    params->ubvec = rmalloc(graph->ncon, "main");
    curptr = params->ubvecstr;
    for (i=0; i<graph->ncon; i++) {
      params->ubvec[i] = strtoreal(curptr, &newptr);
      if (curptr == newptr)
        errexit("Error parsing entry #%"PRIDX" of ubvec [%s] (possibly missing).\n",
            i, params->ubvecstr);
      curptr = newptr;
    }
  }

  /* Setup iptype */
  if (params->iptype == -1) {
    if (params->ptype == METIS_PTYPE_RB) {
      if (graph->ncon == 1)
        params->iptype = METIS_IPTYPE_GROW;
      else
        params->iptype = METIS_IPTYPE_RANDOM;
    }
  }

  GPPrintInfo(params, graph);

  part = imalloc(graph->nvtxs, "main: part");

  METIS_SetDefaultOptions(options);
  options[METIS_OPTION_OBJTYPE] = params->objtype;
  options[METIS_OPTION_CTYPE]   = params->ctype;
  options[METIS_OPTION_IPTYPE]  = params->iptype;
  options[METIS_OPTION_RTYPE]   = params->rtype;
  options[METIS_OPTION_MINCONN] = params->minconn;
  options[METIS_OPTION_CONTIG]  = params->contig;
  options[METIS_OPTION_SEED]    = params->seed;
  options[METIS_OPTION_NITER]   = params->niter;
  options[METIS_OPTION_NCUTS]   = params->ncuts;
  options[METIS_OPTION_UFACTOR] = params->ufactor;
  options[METIS_OPTION_DBGLVL]  = params->dbglvl;

  gk_malloc_init();
  gk_startcputimer(params->parttimer);

  switch (params->ptype) {
    case METIS_PTYPE_RB:
      status = METIS_PartGraphRecursive(&graph->nvtxs, &graph->ncon, graph->xadj,
                   graph->adjncy, graph->vwgt, graph->vsize, graph->adjwgt,
                   &params->nparts, params->tpwgts, params->ubvec, options,
                   &objval, part);
      break;

    case METIS_PTYPE_KWAY:
      status = METIS_PartGraphKway(&graph->nvtxs, &graph->ncon, graph->xadj,
                   graph->adjncy, graph->vwgt, graph->vsize, graph->adjwgt,
                   &params->nparts, params->tpwgts, params->ubvec, options,
                   &objval, part);
      break;

  }

  gk_stopcputimer(params->parttimer);

  if (gk_GetCurMemoryUsed() != 0)
    printf("***It seems that Metis did not free all of its memory! Report this.\n");
  params->maxmemory = gk_GetMaxMemoryUsed();
  gk_malloc_cleanup(0);


  if (status != METIS_OK) {
    printf("\n***Metis returned with an error.\n");
  }
  else {
    if (!params->nooutput) {
      /* Write the solution */
      gk_startcputimer(params->iotimer);
      WritePartition(params->filename, part, graph->nvtxs, params->nparts);
      gk_stopcputimer(params->iotimer);
    }

    GPReportResults(params, graph, part, objval);
  }

  idx_t *r_part = ( idx_t* ) calloc( graph->nvtxs, sizeof( idx_t ) );

  for( i = 0; i < graph->nvtxs; i++ )
  {
       r_part[ i ] = part[ i ];
  }

  FreeGraph(&graph);
  gk_free((void **)&part, LTERM);
  gk_free((void **)&params->filename, &params->tpwgtsfile, &params->tpwgts,
      &params->ubvecstr, &params->ubvec, &params, LTERM);

  return r_part;
}
Beispiel #7
0
int main (int argc, char **argv)
{
	int res, i, j = 0, game_index;
    char *playbackname = NULL;
    char gamenameselection[32];
    int use_cyclone=1;
    int use_drz80_save=0;
   	int use_drz80_snd_save=1;
    int use_drz80;
   	int use_drz80_snd;
    extern int video_scale;
	extern int video_border;
	extern int video_aspect;
	extern int throttle;
	extern int soundcard;
    int use_gui=0;
    int first_run=1;

	kiosk_mode=0;

	{
	    char *abspath = (char*)malloc(PATH_MAX);
		if (!abspath) {
			logerror("Out of memory\n");
		}
	    realpath(argv[0], abspath);
	    char *dirsep = strrchr(abspath, '/');
	    if( dirsep != 0 ) *dirsep = 0;
		chdir(abspath);
		free(abspath);
	}
 
	memset(&options,0,sizeof(options));

	/* these two are not available in mame.cfg */
	errorlog = 0;

	game_index = -1;

	soundcard=-1;

	for (i = 1;i < argc;i++) /* V.V_121997 */
	{
		if (strcasecmp(argv[i],"-log") == 0)
			errorlog = fopen("error.log","wa");
		if (strcasecmp(argv[i],"-nocyclone") == 0)
			use_cyclone=0;
		if (strcasecmp(argv[i],"-drz80") == 0)
			use_drz80_save=1;
		if (strcasecmp(argv[i],"-nodrz80_snd") == 0)
			use_drz80_snd_save=0;
		if (strcasecmp(argv[i],"-scale") == 0)
			video_scale=1;
		if (strcasecmp(argv[i],"-border") == 0)
			video_border=1;
		if (strcasecmp(argv[i],"-aspect") == 0)
			video_aspect=1;
		if (strcasecmp(argv[i],"-nothrottle") == 0)
			throttle=0;
		if (strcasecmp(argv[i],"-nosound") == 0)
			soundcard=0;
        if (strcasecmp(argv[i],"-playback") == 0)
		{
			i++;
			if (i < argc)  /* point to inp file name */
				playbackname = argv[i];
        	}
	}

	if (argc == 1)
		use_gui=1;

	/* check for frontend options */
	if(!use_gui) {
		res = frontend_help (argc, argv);
	
		/* if frontend options were used, return to DOS with the error code */
		if (res != 1234)
		{
			exit (res);
		}
	}

    for (j = 1; j < argc; j++)
    {
        if (argv[j][0] != '-') {
            strcpy(gamenameselection, argv[j]);
            break;
        }
    }

    if(init_SDL()==0) {
        exit(1);
    };
    
gui_loop:
    
    if(use_gui) {
		usleep(1000000/2);
        
        gp2x_joystick_clear();

		//Normally read in the game start but we need some vars
		//setting for the frontend.
		parse_cmdline (argc, argv, 1);
        
        frontend_gui(gamenameselection, first_run);
        
        first_run=0;
        
		usleep(1000000/2);
        
        //Clear input queue
        gp2x_joystick_clear();
    }
    
    /* handle playback which is not available in mame.cfg */
	init_inpdir(); /* Init input directory for opening .inp for playback */

    if (playbackname != NULL)
        options.playback = osd_fopen(playbackname,0,OSD_FILETYPE_INPUTLOG,0);

    /* check for game name embedded in .inp header */
    if (options.playback)
    {
        INP_HEADER inp_header;

        /* read playback header */
        osd_fread(options.playback, &inp_header, sizeof(INP_HEADER));

        if (!isalnum(inp_header.name[0])) /* If first byte is not alpha-numeric */
            osd_fseek(options.playback, 0, SEEK_SET); /* old .inp file - no header */
        else
        {
            for (i = 0; (drivers[i] != 0); i++) /* find game and play it */
			{
                if (strcmp(drivers[i]->name, inp_header.name) == 0)
                {
                    game_index = i;
                    printf("Playing back previously recorded game %s (%s) [press return]\n",
                        drivers[game_index]->name,drivers[game_index]->description);
                    getchar();
                    break;
                }
            }
        }
    }

	/* If not playing back a new .inp file */
    if (game_index == -1)
    {
		/* do we have a driver for this? */
        {
            for (i = 0; drivers[i] && (game_index == -1); i++)
            {
                    if (strcasecmp(gamenameselection,drivers[i]->name) == 0)
                {
                    game_index = i;
                    break;
                }
            }
        }

        if (game_index == -1)
        {
            printf("Game \"%s\" not supported\n", argv[j]);
            return 1;
        }
    }

	/* parse generic (os-independent) options */
	parse_cmdline (argc, argv, game_index);

{	/* Mish:  I need sample rate initialised _before_ rom loading for optional rom regions */
	extern int soundcard;

	if (soundcard == 0) {    /* silence, this would be -1 if unknown in which case all roms are loaded */
		Machine->sample_rate = 0; /* update the Machine structure to show that sound is disabled */
		options.samplerate=0;
	}
}

	/* handle record which is not available in mame.cfg */
	for (i = 1; i < argc; i++)
	{
		if (strcasecmp(argv[i],"-record") == 0)
		{
            i++;
			if (i < argc)
				options.record = osd_fopen(argv[i],0,OSD_FILETYPE_INPUTLOG,1);
		}
	}

    if (options.record)
    {
        INP_HEADER inp_header;

        memset(&inp_header, '\0', sizeof(INP_HEADER));
        strcpy(inp_header.name, drivers[game_index]->name);
        /* MAME32 stores the MAME version numbers at bytes 9 - 11
         * MAME DOS keeps this information in a string, the
         * Windows code defines them in the Makefile.
         */
        /*
        inp_header.version[0] = 0;
        inp_header.version[1] = VERSION;
        inp_header.version[2] = BETA_VERSION;
        */
        osd_fwrite(options.record, &inp_header, sizeof(INP_HEADER));
    }

	/* Replace M68000 by CYCLONE */
	if (use_cyclone)
	{
		for (i=0;i<MAX_CPU;i++)
		{
			int *type=(int*)&(drivers[game_index]->drv->cpu[i].cpu_type);
			if (((*type)&0xff)==CPU_M68000 || ((*type)&0xff)==CPU_M68010 )
			{
				*type=((*type)&(~0xff))|CPU_CYCLONE;
			}
		}
	}

	use_drz80_snd = use_drz80_snd_save;
	use_drz80 = use_drz80_save;	

	// Do not use the DrZ80 core for games that are listed as not compatible
	// in the frontend list
	for (i=0;i<NUMGAMES;i++)
 	{
		if (strcmp(drivers[game_index]->name,fe_drivers[i].name)==0)
		{
			/* ASM cores: 0=None,1=Cyclone,2=DrZ80,3=Cyclone+DrZ80,4=DrZ80(snd),5=Cyclone+DrZ80(snd) */
			if(fe_drivers[i].cores == 0 || fe_drivers[i].cores == 1) 
			{
				use_drz80_snd=0;
				use_drz80=0;
				break;
			}
		}
	}

#if (HAS_DRZ80)
	/* Replace Z80 by DRZ80 */
	if (use_drz80)
	{
		for (i=0;i<MAX_CPU;i++)
		{
			int *type=(int*)&(drivers[game_index]->drv->cpu[i].cpu_type);
			if (((*type)&0xff)==CPU_Z80)
			{
				*type=((*type)&(~0xff))|CPU_DRZ80;
			}
		}
	}

	/* Replace Z80 with DRZ80 only for sound CPUs */
	if (use_drz80_snd)
	{
		for (i=0;i<MAX_CPU;i++)
		{
			int *type=(int*)&(drivers[game_index]->drv->cpu[i].cpu_type);
			if ((((*type)&0xff)==CPU_Z80) && ((*type)&CPU_AUDIO_CPU))
			{
				*type=((*type)&(~0xff))|CPU_DRZ80;
			}
		}
	}
#endif

    /*
		for (i=0;i<MAX_CPU;i++)
		{
			int *type=(int*)&(drivers[game_index]->drv->cpu[i].cpu_type);
			if (((*type)&0xff)==CPU_V30)
			{
				*type=((*type)&(~0xff))|CPU_ARMV30;
			}
		}
		for (i=0;i<MAX_CPU;i++)
		{
			int *type=(int*)&(drivers[game_index]->drv->cpu[i].cpu_type);
			if (((*type)&0xff)==CPU_V33)
			{
				*type=((*type)&(~0xff))|CPU_ARMV33;
			}
		}
    */

    // Remove the mouse usage for certain games
    if ( (strcasecmp(drivers[game_index]->name,"hbarrel")==0) || (strcasecmp(drivers[game_index]->name,"hbarrelw")==0) ||
         (strcasecmp(drivers[game_index]->name,"midres")==0) || (strcasecmp(drivers[game_index]->name,"midresu")==0) ||
         (strcasecmp(drivers[game_index]->name,"midresj")==0) || (strcasecmp(drivers[game_index]->name,"tnk3")==0) ||
         (strcasecmp(drivers[game_index]->name,"tnk3j")==0) || (strcasecmp(drivers[game_index]->name,"ikari")==0) ||
         (strcasecmp(drivers[game_index]->name,"ikarijp")==0) || (strcasecmp(drivers[game_index]->name,"ikarijpb")==0) ||
         (strcasecmp(drivers[game_index]->name,"victroad")==0) || (strcasecmp(drivers[game_index]->name,"dogosoke")==0) ||
         (strcasecmp(drivers[game_index]->name,"gwar")==0) || (strcasecmp(drivers[game_index]->name,"gwarj")==0) ||
         (strcasecmp(drivers[game_index]->name,"gwara")==0) || (strcasecmp(drivers[game_index]->name,"gwarb")==0) ||
         (strcasecmp(drivers[game_index]->name,"bermudat")==0) || (strcasecmp(drivers[game_index]->name,"bermudaj")==0) ||
         (strcasecmp(drivers[game_index]->name,"bermudaa")==0) || (strcasecmp(drivers[game_index]->name,"mplanets")==0) ||
         (strcasecmp(drivers[game_index]->name,"forgottn")==0) || (strcasecmp(drivers[game_index]->name,"lostwrld")==0) ||
         (strcasecmp(drivers[game_index]->name,"gondo")==0) || (strcasecmp(drivers[game_index]->name,"makyosen")==0) ||
         (strcasecmp(drivers[game_index]->name,"topgunr")==0) || (strcasecmp(drivers[game_index]->name,"topgunbl")==0) ||
         (strcasecmp(drivers[game_index]->name,"tron")==0) || (strcasecmp(drivers[game_index]->name,"tron2")==0) ||
         (strcasecmp(drivers[game_index]->name,"kroozr")==0) ||(strcasecmp(drivers[game_index]->name,"crater")==0) ||
         (strcasecmp(drivers[game_index]->name,"dotron")==0) || (strcasecmp(drivers[game_index]->name,"dotrone")==0) ||
         (strcasecmp(drivers[game_index]->name,"zwackery")==0) || (strcasecmp(drivers[game_index]->name,"ikari3")==0) ||
         (strcasecmp(drivers[game_index]->name,"searchar")==0) || (strcasecmp(drivers[game_index]->name,"sercharu")==0) ||
         (strcasecmp(drivers[game_index]->name,"timesold")==0) || (strcasecmp(drivers[game_index]->name,"timesol1")==0) ||
         (strcasecmp(drivers[game_index]->name,"btlfield")==0) || (strcasecmp(drivers[game_index]->name,"aztarac")==0))
    {
        extern int use_mouse;
        use_mouse=0;
    }

    /* go for it */
    printf ("%s (%s)...\n",drivers[game_index]->description,drivers[game_index]->name);
    res = run_game (game_index);

	/* close open files */
	if (errorlog) fclose (errorlog);
	if (options.playback) osd_fclose (options.playback);
	if (options.record)   osd_fclose (options.record);
	if (options.language_file) osd_fclose (options.language_file);

	gp2x_deinit();
    
	game_index = -1;

	if(use_gui) goto gui_loop;
    
	deinit_SDL();
    
	exit (res);
}
Beispiel #8
0
int
main (int argc, char *argv[])
{
    int   fd = -1;
    char *log_identity = argv[0];
    int   log_priority = LOG_INFO;
    int   log_options = LOG_OPT_PRIORITY;

#ifndef NDEBUG
    log_priority = LOG_DEBUG;
    log_options |= LOG_OPT_TIMESTAMP;
#endif /* NDEBUG */
    log_open_file (stderr, log_identity, log_priority, log_options);

    disable_core_dumps ();
    conf = create_conf ();
    parse_cmdline (conf, argc, argv);
    auth_recv_init (conf->auth_server_dir, conf->auth_client_dir,
        conf->got_force);

    if (!conf->got_foreground) {
        fd = daemonize_init (argv[0]);
        if (conf->got_syslog) {
            log_open_file (NULL, NULL, 0, 0);
            log_open_syslog (log_identity, LOG_DAEMON);
        }
        else {
            open_logfile (conf->logfile_name, log_priority, conf->got_force);
        }
    }
    handle_signals ();
    lookup_ip_addr (conf);
    write_pidfile (conf->pidfile_name, conf->got_force);
    if (conf->got_mlockall) {
        lock_memory ();
    }
    crypto_init ();
    if (random_init (conf->seed_name) < 0) {
        if (conf->seed_name) {
            free (conf->seed_name);
            conf->seed_name = NULL;
        }
    }
    create_subkeys (conf);
    conf->gids = gids_create (conf->gids_update_secs, conf->got_group_stat);
    replay_init ();
    timer_init ();
    sock_create (conf);

    if (!conf->got_foreground) {
        daemonize_fini (fd);
    }
    log_msg (LOG_NOTICE, "Starting %s daemon (pid %d)",
        META_ALIAS, (int) getpid ());

    job_accept (conf);

    sock_destroy (conf);
    timer_fini ();
    replay_fini ();
    gids_destroy (conf->gids);
    random_fini (conf->seed_name);
    crypto_fini ();
    destroy_conf (conf);

    log_msg (LOG_NOTICE, "Stopping %s daemon (pid %d)",
        META_ALIAS, (int) getpid ());

    exit (EMUNGE_SUCCESS);
}
Beispiel #9
0
int 
main(int argc, char *argv[])
{
  int            x; 
  int            j = 0;
  int            result;
  DATA           D    = new_data();
  ARRAY          urls = new_array();
  CREW           crew;  
  LINES          *lines;   
  CLIENT         *client; 
  pthread_t      cease; 
  pthread_t      timer;  
  pthread_attr_t scope_attr; 
  void *statusp;
  sigset_t sigs;

  sigemptyset(&sigs);
  sigaddset(&sigs, SIGHUP);
  sigaddset(&sigs, SIGINT);
  sigaddset(&sigs, SIGALRM);
  sigaddset(&sigs, SIGTERM);
  sigaddset(&sigs, SIGPIPE);
  sigprocmask(SIG_BLOCK, &sigs, NULL);

  lines = xcalloc(1, sizeof *lines);
  lines->index   = 0;
  lines->line    = NULL;

  memset(&my, 0, sizeof(struct CONFIG));

  parse_rc_cmdline(argc, argv); 
  if (init_config() < 0) { 
    exit(EXIT_FAILURE); 
  } 
  parse_cmdline(argc, argv);
  ds_module_check(); 

  /**
   * XXX: we should consider moving the following
   * if-checks into the ds_module_check
   */

  if (my.config) {
    show_config(TRUE);    
  }

  if (my.url != NULL) {
    my.length = 1; 
  } else { 
    my.length = read_cfg_file(lines, my.file); 
  }

  //if (my.reps < 0) {
  //  my.reps = my.length;
  //}

  if (my.length == 0) { 
    display_help();
  }

  /* cookie is an EXTERN, defined in setup */ 
  cookie = xcalloc(sizeof(COOKIE), 1); 
  cookie->first = NULL;
  if ((result = pthread_mutex_init( &(cookie->mutex), NULL)) !=0) {
    NOTIFY(FATAL, "pthread_mutex_init" );
  } 

  /* memory allocation for threads and clients */
  client = xcalloc(my.cusers, sizeof(CLIENT));
  if ((crew = new_crew(my.cusers, my.cusers, FALSE)) == NULL) {
    NOTIFY(FATAL, "unable to allocate memory for %d simulated browser", my.cusers);  
  }

  /** 
   * determine the source of the url(s),
   * command line or file, and add them
   * to the urls struct.
   */

  if (my.url != NULL) {
    URL tmp = new_url(my.url);
    url_set_ID(tmp, 0);
    if (my.get && url_get_method(tmp) != POST && url_get_method(tmp) != PUT) {
      url_set_method(tmp, my.method); 
    }
    array_npush(urls, tmp, URLSIZE); // from cmd line
  } else { 
    for (x = 0; x < my.length; x++) {
      URL tmp = new_url(lines->line[x]);
      url_set_ID(tmp, x);
      array_npush(urls, tmp, URLSIZE);
    }
  } 

  /**
   * display information about the siege
   * to the user and prepare for verbose 
   * output if necessary.
   */
  if (!my.get && !my.quiet) {
    fprintf(stderr, "** "); 
    display_version(FALSE);
    fprintf(stderr, "** Preparing %d concurrent users for battle.\n", my.cusers);
    fprintf(stderr, "The server is now under siege...");
    if (my.verbose) { fprintf(stderr, "\n"); }
  }

  /**
   * record start time before spawning threads
   * as the threads begin hitting the server as
   * soon as they are created.
   */
  data_set_start(D);

  /**
   * for each concurrent user, spawn a thread and
   * loop until condition or pthread_cancel from the
   * handler thread.
   */
  pthread_attr_init(&scope_attr);
  pthread_attr_setscope(&scope_attr, PTHREAD_SCOPE_SYSTEM);
#if defined(_AIX)
  /* AIX, for whatever reason, defies the pthreads standard and  *
   * creates threads detached by default. (see pthread.h on AIX) */
  pthread_attr_setdetachstate(&scope_attr, PTHREAD_CREATE_JOINABLE);
#endif

  /** 
   * invoke OpenSSL's thread safety
   */
#ifdef HAVE_SSL
  SSL_thread_setup();
#endif

  /**
   * create the signal handler and timer;  the
   * signal handler thread (cease) responds to
   * ctrl-C (sigterm) and the timer thread sends
   * sigterm to cease on time out.
   */
  if ((result = pthread_create(&cease, NULL, (void*)sig_handler, (void*)crew)) < 0) {
    NOTIFY(FATAL, "failed to create handler: %d\n", result);
  }
  if (my.secs > 0) {
    if ((result = pthread_create(&timer, NULL, (void*)siege_timer, (void*)cease)) < 0) {
      NOTIFY(FATAL, "failed to create handler: %d\n", result);
    } 
  }

  /**
   * loop until my.cusers and create a corresponding thread...
   */  
  for (x = 0; x < my.cusers && crew_get_shutdown(crew) != TRUE; x++) {
    client[x].id              = x; 
    client[x].bytes           = 0;
    client[x].time            = 0.0;
    client[x].hits            = 0;
    client[x].code            = 0;
    client[x].ok200           = 0;   
    client[x].fail            = 0; 
    if (my.reps > 0 ) {
      /** 
       * Traditional -r/--reps where each user
       * loops through every URL in the file. 
       */
      client[x].urls = urls;
    } else {
      /**
       * -r once/--reps=once where each URL
       * in the file is hit only once...
       */
      int   len = (array_length(urls)/my.cusers); 
      ARRAY tmp = new_array();
      for ( ; j < ((x+1) * len) && j < (int)array_length(urls); j++) {
        URL u = array_get(urls, j);
        if (u != NULL && url_get_hostname(u) != NULL && strlen(url_get_hostname(u)) > 1) {
          array_npush(tmp, array_get(urls, j), URLSIZE);    
        }
      } 
      client[x].urls = tmp;
    }
    client[x].auth.www        = 0;
    client[x].auth.proxy      = 0;
    client[x].auth.type.www   = BASIC;
    client[x].auth.type.proxy = BASIC;
    client[x].rand_r_SEED     = urandom();
    result = crew_add(crew, (void*)start_routine, &(client[x]));
    if (result == FALSE) { 
      my.verbose = FALSE;
      fprintf(stderr, "Unable to spawn additional threads; you may need to\n");
      fprintf(stderr, "upgrade your libraries or tune your system in order\n"); 
      fprintf(stderr, "to exceed %d users.\n", my.cusers);
      NOTIFY(FATAL, "system resources exhausted"); 
    }
  } /* end of for pthread_create */

  crew_join(crew, TRUE, &statusp);

#ifdef HAVE_SSL
  SSL_thread_cleanup();
#endif

  /**
   * collect all the data from all the threads that
   * were spawned by the run.
   */
  for (x = 0; x < ((crew_get_total(crew) > my.cusers || 
                    crew_get_total(crew)==0 ) ? my.cusers : crew_get_total(crew)); x++) {
    data_increment_count(D, client[x].hits);
    data_increment_bytes(D, client[x].bytes);
    data_increment_total(D, client[x].time);
    data_increment_code (D, client[x].code);
    data_increment_ok200(D, client[x].ok200);
    data_increment_fail (D, client[x].fail);
    data_set_highest    (D, client[x].himark);
    data_set_lowest     (D, client[x].lomark);
    client[x].rand_r_SEED = urandom();
  } /* end of stats accumulation */
  
  /**
   * record stop time
   */
  data_set_stop(D);

  /**
   * cleanup crew
   */ 
  crew_destroy(crew);

  for (x = 0; x < my.cusers; x++) {
    // XXX: TODO
    //digest_challenge_destroy(client[x].auth.wwwchlg);
    //digest_credential_destroy(client[x].auth.wwwcred);
    //digest_challenge_destroy(client[x].auth.proxychlg);
    //digest_credential_destroy(client[x].auth.proxycred);
  }
  array_destroy(my.lurl);
  xfree(client);

  if (my.get) {
    if (data_get_ok200(D) > 0) {
       exit(EXIT_SUCCESS);
    } else {
      if (!my.quiet) echo("[done]\n");
      exit(EXIT_FAILURE);
    }
  }

  /**
   * take a short nap  for  cosmetic  effect
   * this does NOT affect performance stats.
   */
  pthread_usleep_np(10000);
  if (my.verbose)
    fprintf(stderr, "done.\n");
  else
    fprintf(stderr, "\b      done.\n");

  /**
   * prepare and print statistics.
   */
  if (my.failures > 0 && my.failed >= my.failures) {
    fprintf(stderr, "%s aborted due to excessive socket failure; you\n", program_name);
    fprintf(stderr, "can change the failure threshold in $HOME/.%src\n", program_name);
  }
  fprintf(stderr, "\nTransactions:\t\t%12u hits\n",        data_get_count(D));
  fprintf(stderr, "Availability:\t\t%12.2f %%\n",          data_get_count(D)==0 ? 0 :
                                                           (double)data_get_count(D) /
                                                           (data_get_count(D)+my.failed)
                                                           *100
  );
  fprintf(stderr, "Elapsed time:\t\t%12.2f secs\n",        data_get_elapsed(D));
  fprintf(stderr, "Data transferred:\t%12.2f MB\n",        data_get_megabytes(D)); /*%12llu*/
  fprintf(stderr, "Response time:\t\t%12.2f secs\n",       data_get_response_time(D));
  fprintf(stderr, "Transaction rate:\t%12.2f trans/sec\n", data_get_transaction_rate(D));
  fprintf(stderr, "Throughput:\t\t%12.2f MB/sec\n",        data_get_throughput(D));
  fprintf(stderr, "Concurrency:\t\t%12.2f\n",              data_get_concurrency(D));
  fprintf(stderr, "Successful transactions:%12u\n",        data_get_code(D)); 
  if (my.debug) {
    fprintf(stderr, "HTTP OK received:\t%12u\n",             data_get_ok200(D));
  }
  fprintf(stderr, "Failed transactions:\t%12u\n",          my.failed);
  fprintf(stderr, "Longest transaction:\t%12.2f\n",        data_get_highest(D));
  fprintf(stderr, "Shortest transaction:\t%12.2f\n",       data_get_lowest(D));
  fprintf(stderr, " \n");
  if(my.mark)    mark_log_file(my.markstr);
  if(my.logging) log_transaction(D);

  data_destroy(D);
  if (my.url == NULL) {
    for (x = 0; x < my.length; x++)
      xfree(lines->line[x]);
    xfree(lines->line);
    xfree(lines);
  } else {
    xfree(lines->line);
    xfree(lines);
  }

  pthread_mutex_destroy( &(cookie->mutex));

  /** 
   * I should probably take a deeper look 
   * at cookie content to free it but at 
   * this point we're two lines from exit
   */
  xfree (cookie);
  xfree (my.url);

  exit(EXIT_SUCCESS);  
} /* end of int main **/
Beispiel #10
0
int main(int argc, char **argv)
{
  char *platformFile = NULL;
  int totalHosts, totalLinks;
  int timings=0;
  int downgrade = 0;
  int version = 3;
  const char *link_ctn = link_ctn_v3;
  unsigned int i;
  xbt_dict_t props = NULL;
  xbt_dict_cursor_t cursor = NULL;
  xbt_lib_cursor_t cursor_src = NULL;
  xbt_lib_cursor_t cursor_dst = NULL;
  char *src,*dst,*key,*data;
  sg_routing_edge_t value1;
  sg_routing_edge_t value2;

  const SD_workstation_t *hosts;
  const SD_link_t *links;
  xbt_os_timer_t parse_time = xbt_os_timer_new();

  setvbuf(stdout, NULL, _IOLBF, 0);

  SD_init(&argc, argv);

  if (parse_cmdline(&timings, &downgrade, &platformFile, argc, argv) || !platformFile) {
    xbt_die("Invalid command line arguments: expected [--timings|--downgrade] platformFile");
  }
 
  XBT_DEBUG("%d,%d,%s", timings, downgrade, platformFile);

  if (downgrade) {
    version = 2;
    link_ctn = link_ctn_v2;
  }

  create_environment(parse_time, platformFile);

  if (timings) {
    XBT_INFO("Parsing time: %fs (%d hosts, %d links)",
          xbt_os_timer_elapsed(parse_time),SD_workstation_get_number(),SD_link_get_number());
  } else {
    printf("<?xml version='1.0'?>\n");
    printf("<!DOCTYPE platform SYSTEM \"http://simgrid.gforge.inria.fr/simgrid.dtd\">\n");
    printf("<platform version=\"%d\">\n", version);
    if (!downgrade)
      printf("<AS id=\"AS0\" routing=\"Full\">\n");

    // Hosts
    totalHosts = SD_workstation_get_number();
    hosts = SD_workstation_get_list();
    qsort((void *) hosts, totalHosts, sizeof(SD_workstation_t),
        name_compare_hosts);

    for (i = 0; i < totalHosts; i++) {
      printf("  <host id=\"%s\" power=\"%.0f\"",
          SD_workstation_get_name(hosts[i]),
          SD_workstation_get_power(hosts[i]));
      props = SD_workstation_get_properties(hosts[i]);
      if (props && !xbt_dict_is_empty(props)) {
        printf(">\n");
        xbt_dict_foreach(props, cursor, key, data) {
          printf("    <prop id=\"%s\" value=\"%s\"/>\n", key, data);
        }
        printf("  </host>\n");
      } else {
Beispiel #11
0
/**
 * main
 */
int main(int argc, const char **argv)
{
   // Our main data storage vessel..
   RASPIVID_STATE state;

   MMAL_STATUS_T status = -1;
   MMAL_PORT_T *camera_preview_port = NULL;
   MMAL_PORT_T *camera_video_port = NULL;
   MMAL_PORT_T *camera_still_port = NULL;
   MMAL_PORT_T *preview_input_port = NULL;
   MMAL_PORT_T *encoder_input_port = NULL;
   MMAL_PORT_T *encoder_output_port = NULL;
   FILE *output_file = NULL;

   bcm_host_init();

   // Register our application with the logging system
   vcos_log_register("RaspiVid", VCOS_LOG_CATEGORY);

   signal(SIGINT, signal_handler);

   default_status(&state);

   // Do we have any parameters
   if (argc == 1)
   {
      fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);

      display_valid_parameters(basename(argv[0]));
      exit(0);
   }

   // Parse the command line and put options in to our status structure
   if (parse_cmdline(argc, argv, &state))
   {
      status = -1;
      exit(0);
   }

   if (state.verbose)
   {
      fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);
      dump_status(&state);
   }

   // OK, we have a nice set of parameters. Now set up our components
   // We have three components. Camera, Preview and encoder.

   if (!create_camera_component(&state))
   {
      vcos_log_error("%s: Failed to create camera component", __func__);
   }
   else if ((status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);
   }
//Me    else if ((status = create_encoder_component(&state)) != MMAL_SUCCESS)
//Me    {
//Me       vcos_log_error("%s: Failed to create encode component", __func__);
//Me       raspipreview_destroy(&state.preview_parameters);
//Me       destroy_camera_component(&state);
//Me    }
   else
   {
      PORT_USERDATA callback_data;

      if (state.verbose)
         fprintf(stderr, "Starting component connection stage\n");

      camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];
      preview_input_port  = state.preview_parameters.preview_component->input[0];
//Me       encoder_input_port  = state.encoder_component->input[0];
//Me       encoder_output_port = state.encoder_component->output[0];

      if (state.preview_parameters.wantPreview )
      {
         if (state.verbose)
         {
            fprintf(stderr, "Connecting camera preview port to preview input port\n");
            fprintf(stderr, "Starting video preview\n");
         }

        // Connect camera to preview
        status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);
      }
      else
      {
        status = MMAL_SUCCESS;
      }

      if (status == MMAL_SUCCESS)
      {
         if (state.verbose)
            fprintf(stderr, "Connecting camera stills port to encoder input port\n");

//Me          // Now connect the camera to the encoder
//Me          status = connect_ports(camera_video_port, encoder_input_port, &state.encoder_connection);
//Me 
//Me          if (status != MMAL_SUCCESS)
//Me          {
//Me             vcos_log_error("%s: Failed to connect camera video port to encoder input", __func__);
//Me             goto error;
//Me          }
//Me 
         if (state.filename)
         {
            if (state.filename[0] == '-')
            {
               output_file = stdout;

               // Ensure we don't upset the output stream with diagnostics/info
               state.verbose = 0;
            }
            else
            {
               if (state.verbose)
                  fprintf(stderr, "Opening output file \"%s\"\n", state.filename);

               output_file = fopen(state.filename, "wb");
            }

            if (!output_file)
            {
               // Notify user, carry on but discarding encoded output buffers
               vcos_log_error("%s: Error opening output file: %s\nNo output file will be generated\n", __func__, state.filename);
            }
         }
		 
		 VCOS_STATUS_T vcos_status;
		 
         // Set up our userdata - this is passed though to the callback where we need the information.
         callback_data.file_handle = output_file;
         callback_data.pstate = &state;
         callback_data.abort = 0;
		 
		 vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
		 vcos_assert(vcos_status == VCOS_SUCCESS);

         camera_video_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

         if (state.verbose)
            fprintf(stderr, "Enabling encoder output port\n");

//Me          // Enable the encoder output port and tell it its callback function
//Me          status = mmal_port_enable(encoder_output_port, encoder_buffer_callback);
//Me 
//Me          if (status != MMAL_SUCCESS)
//Me          {
//Me             vcos_log_error("Failed to setup encoder output");
//Me             goto error;
//Me          }
//Me 
//Me          if (state.demoMode)
//Me          {
//Me             // Run for the user specific time..
//Me             int num_iterations = state.timeout / state.demoInterval;
//Me             int i;
//Me 
//Me             if (state.verbose)
//Me                fprintf(stderr, "Running in demo mode\n");
//Me 
//Me             for (i=0;state.timeout == 0 || i<num_iterations;i++)
//Me             {
//Me                raspicamcontrol_cycle_test(state.camera_component);
//Me                vcos_sleep(state.demoInterval);
//Me             }
//Me          }
//Me          else
//Me          {
            // Only encode stuff if we have a filename and it opened
            if (output_file)
            {
               int wait;

               if (state.verbose)
                  fprintf(stderr, "Starting video capture\n");

               if (mmal_port_parameter_set_boolean(camera_video_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
               {
                  goto error;
               }

               // Send all the buffers to the video port
               {
                  int num = mmal_queue_length(state.video_pool->queue);
                  int q;
                  for (q=0;q<num;q++)
                  {
                     MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.video_pool->queue);

                     if (!buffer)
                        vcos_log_error("Unable to get a required buffer %d from pool queue", q);

                     if (mmal_port_send_buffer(camera_video_port, buffer)!= MMAL_SUCCESS)
                        vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);

                  }
               }

               // Now wait until we need to stop. Whilst waiting we do need to check to see if we have aborted (for example
               // out of storage space)
               // Going to check every ABORT_INTERVAL milliseconds

               for (wait = 0; state.timeout == 0 || wait < state.timeout; wait+= ABORT_INTERVAL)
               {
                  vcos_sleep(ABORT_INTERVAL);
                  if (callback_data.abort)
                     break;
               }

               if (state.verbose)
                  fprintf(stderr, "Finished capture\n");
            }
            else
            {
               if (state.timeout)
                  vcos_sleep(state.timeout);
               else
                  for (;;) vcos_sleep(ABORT_INTERVAL);
            }
//Me          }
      }
      else
      {
         mmal_status_to_int(status);
         vcos_log_error("%s: Failed to connect camera to preview", __func__);
      }

error:

      mmal_status_to_int(status);

      if (state.verbose)
         fprintf(stderr, "Closing down\n");

      // Disable all our ports that are not handled by connections
      check_disable_port(camera_still_port);
//Me       check_disable_port(encoder_output_port);
//Me 
      if (state.preview_parameters.wantPreview )
         mmal_connection_destroy(state.preview_connection);
//Me       mmal_connection_destroy(state.encoder_connection);

      // Can now close our file. Note disabling ports may flush buffers which causes
      // problems if we have already closed the file!
      if (output_file && output_file != stdout)
         fclose(output_file);

      /* Disable components */
//Me       if (state.encoder_component)
//Me          mmal_component_disable(state.encoder_component);
//Me 
      if (state.preview_parameters.preview_component)
         mmal_component_disable(state.preview_parameters.preview_component);

      if (state.camera_component)
         mmal_component_disable(state.camera_component);

//Me       destroy_encoder_component(&state);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);

      if (state.verbose)
         fprintf(stderr, "Close down completed, all components disconnected, disabled and destroyed\n\n");
   }

   if (status != 0)
      raspicamcontrol_check_configuration(128);

   return 0;
}
Beispiel #12
0
int main(int argc, char *argv[])
{
	int err;
	done = 0;
	snd_pcm_t *handle;
	FILE *sound_in_fd = NULL;
	FILE *sound_out_fd = NULL;
	int channels;
	short *buffer = NULL;
	int buffer_l;
	int buffer_read;
	struct serial_state_t *serial = NULL;
	struct ipc_state_t *ipc = NULL;
	struct receiver *rx_a = NULL;
	struct receiver *rx_b = NULL;
#ifdef HAVE_PULSEAUDIO
	pa_simple *pa_dev = NULL;
#endif
	
	/* command line */
	parse_cmdline(argc, argv);
	
	/* open syslog, write an initial log message and read configuration */
	open_log(logname, 0);
	hlog(LOG_NOTICE, "Starting up...");
	if (read_config()) {
		hlog(LOG_CRIT, "Initial configuration failed.");
		exit(1);
	}
	
	/* fork a daemon */
	if (fork_a_daemon) {
		int i = fork();
		if (i < 0) {
			hlog(LOG_CRIT, "Fork to background failed: %s", strerror(errno));
			fprintf(stderr, "Fork to background failed: %s\n", strerror(errno));
			exit(1);
		} else if (i == 0) {
			/* child */
			/* write pid file, now that we have our final pid... might fail, which is critical */
			hlog(LOG_DEBUG, "Writing pid...");
			if (!writepid(pidfile))
				exit(1);
		} else {
			/* parent, quitting */
			hlog(LOG_DEBUG, "Forked daemon process %d, parent quitting", i);
			exit(0);
		}
	}
	
	
	signal(SIGINT, closedown);
	signal(SIGPIPE, brokenconnection);
	
	/* initialize position cache for timed JSON AIS transmission */
	if (uplink_config) {
		hlog(LOG_DEBUG, "Initializing cache...");
		if (cache_init())
			exit(1);
		hlog(LOG_DEBUG, "Initializing jsonout...");
		if (jsonout_init())
			exit(1);
	}
	
	/* initialize serial port for NMEA output */
	if (serial_port)
		serial = serial_init();

	/* initialize Unix domain socket for communication with gnuaisgui */
	ipc = gnuais_ipc_init();
	if(ipc == 0){
		hlog(LOG_ERR, "Could not open Unix Domain Socket");
	}
	
	/* initialize the AIS decoders */
	if (sound_channels != SOUND_CHANNELS_MONO) {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 2, 0,serial,ipc);
		hlog(LOG_DEBUG, "Initializing demodulator B");
		rx_b = init_receiver('B', 2, 1,serial,ipc);
		channels = 2;
	} else {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 1, 0,serial,ipc);
		channels = 1;
	}
#ifdef HAVE_PULSEAUDIO
	if(sound_device != NULL && ((strcmp("pulse",sound_device) == 0) || (strcmp("pulseaudio",sound_device) == 0))){
		if((pa_dev = pulseaudio_initialize()) == NULL){
			hlog(LOG_CRIT, "Error opening pulseaudio device");
			return -1;
		}
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	}
	else if (sound_device){
#else
	if (sound_device){
#endif

		if ((err = snd_pcm_open(&handle, sound_device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
			hlog(LOG_CRIT, "Error opening sound device (%s)", sound_device);
			return -1;
		}
		
		if (input_initialize(handle, &buffer, &buffer_l) < 0)
			return -1;
	} else if (sound_in_file) {
		if ((sound_in_fd = fopen(sound_in_file, "r")) == NULL) {
			hlog(LOG_CRIT, "Could not open sound file %s: %s", sound_in_file, strerror(errno));
			return -1;
		}
		hlog(LOG_NOTICE, "Reading audio from file: %s", sound_in_file);
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	} else {
		hlog(LOG_CRIT, "Neither sound device or sound file configured.");
		return -1;
	}
	
	if (sound_out_file) {
		if ((sound_out_fd = fopen(sound_out_file, "w")) == NULL) {
			hlog(LOG_CRIT, "Could not open sound output file %s: %s", sound_out_file, strerror(errno));
			return -1;
		}
		hlog(LOG_NOTICE, "Recording audio to file: %s", sound_out_file);
	}
	
#ifdef HAVE_MYSQL
	if (mysql_db) {
		hlog(LOG_DEBUG, "Saving to MySQL database \"%s\"", mysql_db);
		if (!(my = myout_init()))
			return -1;
			
		if (mysql_keepsmall)
			hlog(LOG_DEBUG, "Updating database rows only.");
		else
			hlog(LOG_DEBUG, "Inserting data to database.");
			
		if (mysql_oldlimit)
			hlog(LOG_DEBUG, "Deleting data older than %d seconds", mysql_oldlimit);
	}
#endif
	
	hlog(LOG_NOTICE, "Started");
	
	while (!done) {
		if (sound_in_fd) {
			buffer_read = fread(buffer, channels * sizeof(short), buffer_l, sound_in_fd);
			if (buffer_read <= 0)
				done = 1;
		} 
#ifdef HAVE_PULSEAUDIO
		else if (pa_dev){
			buffer_read = pulseaudio_read(pa_dev, buffer, buffer_l);
		}
#endif
		else {
			buffer_read = input_read(handle, buffer, buffer_l);
			//printf("read %d\n", buffer_read);
		}
		if (buffer_read <= 0)
			continue;
		
		if (sound_out_fd) {
			fwrite(buffer, channels * sizeof(short), buffer_read, sound_out_fd);
		}
		
		if (sound_channels == SOUND_CHANNELS_MONO) {
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_RIGHT) {
			/* ch a/0/right */
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_LEFT) {	
			/* ch b/1/left */
			receiver_run(rx_b, buffer, buffer_read);
		}
	}
	
	hlog(LOG_NOTICE, "Closing down...");
	if (sound_in_fd) {
		fclose(sound_in_fd);
	}
#ifdef HAVE_PULSEAUDIO
	else if (pa_dev) {
		pulseaudio_cleanup(pa_dev);
	}
#endif
	else {
		input_cleanup(handle);
		handle = NULL;
	}

	
	if (sound_out_fd)
		fclose(sound_out_fd);
	
	hfree(buffer);

	gnuais_ipc_deinit(ipc);
	
	if (serial)
		serial_close(serial);
	
	if (uplink_config)
		jsonout_deinit();
	
	if (cache_positions)
		cache_deinit();
	
	if (rx_a) {
		struct demod_state_t *d = rx_a->decoder;
		hlog(LOG_INFO,
			"A: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	if (rx_b) {
		struct demod_state_t *d = rx_b->decoder;
		hlog(LOG_INFO,
			"B: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	free_receiver(rx_a);
	free_receiver(rx_b);
	
	free_config();
	close_log(0);
	
	return 0;
}
Beispiel #13
0
int
main(int argc, char **argv)
{
	thread_t thread;

	/* Allocate the room */
	req = (REQ *) MALLOC(sizeof (REQ));

	/* Preset (potentially) non-zero defaults */
	req->hash = hash_default;

	/* Command line parser */
	if (!parse_cmdline(argc, argv, req)) {
		FREE(req);
		exit(0);
	}

	/* Check minimum configuration need */
	if (!req->addr_ip && !req->addr_port && !req->url) {
		FREE(req);
		exit(0);
	}

	/* Init the reference timer */
	req->ref_time = timer_tol(timer_now());
	DBG("Reference timer = %lu\n", req->ref_time);

	/* Init SSL context */
	init_ssl();

	/* Signal handling initialization  */
	signal_init();

	/* Create the master thread */
	master = thread_make_master();

	/* Register the GET request */
	init_sock();

	/*
	 * Processing the master thread queues,
	 * return and execute one ready thread.
	 * Run until error, used for debuging only.
	 * Note that not calling launch_scheduler() does
	 * not activate SIGCHLD handling, however, this
	 * is no issue here.
	 */
	while (thread_fetch(master, &thread))
		thread_call(&thread);

	/* Finalize output informations */
	if (req->verbose)
		printf("Global response time for [%s] =%lu\n",
		       req->url, req->response_time - req->ref_time);

	/* exit cleanly */
	SSL_CTX_free(req->ctx);
	free_sock(sock);
	FREE(req);
	exit(0);
}
int WINAPI WinMain(HINSTANCE this_instance, HINSTANCE prev_instance,
#ifdef _WIN32_WCE
        LPWSTR lpCmdLine,
#else
        LPSTR lpCmdLine,
#endif
        int nCmdShow) {
    LPSTR command_line;
    char *c, stunnel_exe_path[MAX_PATH];
#ifndef _WIN32_WCE
    char *errmsg;
#endif

    (void)prev_instance; /* skip warning about unused parameter */
    (void)nCmdShow; /* skip warning about unused parameter */

    str_init(); /* initialize per-thread string management */
    ghInst=this_instance;
#ifdef _WIN32_WCE
    command_line=tstr2str(lpCmdLine);
#else
    command_line=lpCmdLine;
#endif

    parse_cmdline(command_line); /* setup global cmdline structure */

    GetModuleFileName(0, stunnel_exe_path, MAX_PATH);

#ifndef _WIN32_WCE
    /* find previous instances of the same executable */
    if(!cmdline.service && !cmdline.install && !cmdline.uninstall &&
            !cmdline.start && !cmdline.stop) {
        EnumWindows(enum_windows, (LPARAM)stunnel_exe_path);
        if(cmdline.exit)
            return 0; /* in case EnumWindows didn't find a previous instance */
    }
#endif

    /* set current working directory and engine path */
    c=strrchr(stunnel_exe_path, '\\'); /* last backslash */
    if(c) /* found */
        c[1]='\0'; /* truncate program name */
#ifndef _WIN32_WCE
    if(!SetCurrentDirectory(stunnel_exe_path)) {
        errmsg=str_printf("Cannot set directory to %s", stunnel_exe_path);
        message_box(errmsg, MB_ICONERROR);
        str_free(errmsg);
        return 1;
    }
#endif
    _putenv_s("OPENSSL_ENGINES", stunnel_exe_path);

    if(initialize_winsock())
        return 1;

#ifndef _WIN32_WCE
    if(cmdline.service) /* "-service" must be processed before "-install" */
        return service_initialize();
    if(cmdline.install)
        return service_install(command_line);
    if(cmdline.uninstall)
        return service_uninstall();
    if(cmdline.start)
        return service_start();
    if(cmdline.stop)
        return service_stop();
#endif
    return gui_loop();
}
Beispiel #15
0
void
i686_kmain(unsigned long magic, multiboot_info_t *info) {

  bootvideo_cls();

  parse_cmdline(info->cmdline);

  if (use_serial)
    i686_tty_init(0, 9600);

  i686_kernel.debug = i686_debug;

  if (magic != MULTIBOOT_BOOTLOADER_MAGIC) {
    i686_debug("Not booted from multiboot loader!\n");
    while (1);
  }
 
  i686_debug("mods_addr: %x\nmod_start: %x\n", info->mods_addr,
      0);

  i686_kernel.mutex = &i686_mutex;
  i686_kernel.bsp = (struct cpu *)i686_cpu_alloc();
  i686_kernel.bsp->kvirt = i686_virtmem_init(&i686_kernel);
  i686_kernel.phys = i686_physmem_alloc(&i686_kernel, info);

  kmem_init(i686_kernel.bsp->allocator);
  i686_kernel.bsp->v.init(i686_kernel.bsp);

  i686_debug("Location GDT entry: %x\n", ((struct i686_cpu *)i686_kernel.bsp)->gdt);

  virtaddr_t a;
  physaddr_t p;
  virtmem_error_t e1 = virtmem_kernel_alloc(i686_kernel.bsp->kvirt, &a, 1);
  assert(e1 == VIRTMEM_SUCCESS);
  physmem_error_t e2 = physmem_page_alloc(i686_kernel.bsp->localmem, 0, &p);
  assert(e2 == PHYSMEM_SUCCESS);
  virtmem_kernel_map_virt_to_phys(i686_kernel.bsp->kvirt, p, a);
  i686_debug("Allocated address: %x(->%x)\n", a, p);

  char *s = (char *)a;

  strcpy(s, "This shows the validity of this memory");
  i686_debug("%x contains: %s\n", a, s);

  struct kmem_cache *s1 = kmem_alloc(i686_kernel.bsp->allocator);
  kmem_cache_init(i686_kernel.bsp->allocator,
      s1, i686_kernel.bsp, "test", 128, NULL, NULL);

  char *t1 = kmem_cache_alloc(s1);
  i686_debug("cache at %x provided us with %x\n", s1, t1);
  strcpy(t1, "This shows the validity of the slab allocation");
  i686_debug("%x contains: %s\n", t1, t1);

  i686_address_space_init();
  struct address_space *as;
  struct memory_region *mr;
  address_space_alloc(&as);
  memory_region_alloc(&mr);

  e1 = virtmem_kernel_alloc(i686_kernel.bsp->kvirt, &a, 1);
  virtmem_kernel_map_virt_to_phys(i686_kernel.bsp->kvirt, (physaddr_t)as->pd, a);
  
  address_space_init_region(as, mr, (virtaddr_t)0x1000000, 0x2000);
  memory_region_set_flags(mr, 1, 1);
  memory_region_map(as, mr, NULL);

  const char *teststr = "This is a test string to be copied to userspace.";
  char testcpybuf[128];
  char opcodes[] = {0xeb, 0xfe};
  virtmem_copy_kernel_to_user(i686_kernel.bsp->kvirt, as->pd, (void *)0x1000ffc, 
      (const void *)teststr, strlen(teststr) + 1);
  virtmem_copy_user_to_kernel(i686_kernel.bsp->kvirt, (void *)&testcpybuf, 
      as->pd, (const void *)0x1000ffc, strlen(teststr) + 1);
  i686_debug("testcpybuf contains '%s'\n", testcpybuf);
  virtmem_copy_kernel_to_user(i686_kernel.bsp->kvirt, as->pd, (void *)0x1000000, 
      (const void *)opcodes, 2);


  struct thread *thr1;
  scheduler_thread_alloc(cpu()->sched, &thr1);
  thread_init(thr1, as);
  thr1->state = THREAD_RUNNABLE;
  scheduler_thread_add(cpu()->sched, thr1);
  scheduler_reschedule(cpu()->sched);
  virtmem_user_setup_kernelspace(i686_kernel.bsp->kvirt, as->pd);
  virtmem_set_context(i686_kernel.bsp->kvirt, as->pd);
  scheduler_resume(cpu()->sched);
  while (1);
}
Beispiel #16
0
int main(int argc, char **argv)
{
    daemonize_close_stdin();

    parse_cmdline(argc, argv);

    if (!file_read_config())
        g_error("cannot read configuration file\n");

    log_init(file_config.log, file_config.verbose);

    daemonize_init(file_config.daemon_user, file_config.pidfile);

    if (!file_config.no_daemon)
        daemonize_detach();

    daemonize_write_pidfile();
    daemonize_set_user();

#ifndef NDEBUG
    if (!file_config.no_daemon)
#endif
        daemonize_close_stdout_stderr();

    main_loop = g_main_loop_new(NULL, FALSE);

    lmc_connect(file_config.host, file_config.port);
    http_client_init();
    as_init(file_config.scrobblers);

    setup_signals();

    timer = g_timer_new();

    /* set up timeouts */

    save_source_id = g_timeout_add_seconds(file_config.journal_interval,
                                           timer_save_journal, NULL);

    /* run the main loop */

    g_main_loop_run(main_loop);

    /* cleanup */

    g_message("shutting down\n");

    g_source_remove(save_source_id);
    g_main_loop_unref(main_loop);

    g_timer_destroy(timer);

    as_save_cache();
    as_cleanup();
    http_client_finish();
    lmc_disconnect();
    file_cleanup();
    log_deinit();

    daemonize_finish();

    return 0;
}
Beispiel #17
0
int main(int argc, char** argv)
{
    if(argc<2) {
        print_help();
        return 0;
    }
    parse_cmdline(argc,argv);
    if(g_flags.rand_gen)
        test_curand_raw(g_flags.n, g_flags.mc_iterations, g_flags.nr_dev);
    else if(g_flags.an_coding) { /* AN-coding */
        if(g_flags.mc_search_bound>0.0)
            ancoding_mc_search();
        else if(g_flags.mc_search_super_A)
            ancoding_mc_search_super_A();
        else if(g_flags.with_mc) {
            if(g_flags.with_grid)
                run_ancoding_grid(g_flags.with_grid,
                                  g_flags.n,
                                  g_flags.mc_iterations, g_flags.mc_iterations_2,
                                  g_flags.A,
                                  g_flags.verbose,nullptr,nullptr,nullptr,
                                  g_flags.file_output,
                                  g_flags.nr_dev);
            else
                run_ancoding_mc(g_flags.n,
                                g_flags.mc_iterations,
                                g_flags.A,
                                g_flags.verbose,nullptr,nullptr,nullptr,
                                g_flags.file_output,
                                g_flags.nr_dev);
        } else if(g_flags.use_cpu)
            run_ancoding_cpu(g_flags.n,
                             g_flags.A,
                             g_flags.verbose, nullptr, nullptr,
                             g_flags.file_output);
        else
            run_ancoding(g_flags.n,
                         g_flags.A,
                         g_flags.verbose, nullptr, nullptr,
                         g_flags.file_output,
                         g_flags.nr_dev);
    } else if(g_flags.h_coding==1) { /* Ext Hamming Code */
        if(g_flags.use_cpu)
            run_hamming_cpu(g_flags.n,g_flags.with_1bit,g_flags.file_output);
        else if(g_flags.with_grid)
        {
            run_hamming_grid(g_flags.n,
                             g_flags.with_1bit,
                             g_flags.mc_iterations,
                             g_flags.file_output,
                             g_flags.nr_dev);
        } else if(g_flags.with_mc)
            run_hamming_mc(g_flags.n,
                           g_flags.with_1bit,
                           g_flags.mc_iterations,
                           g_flags.file_output,
                           g_flags.nr_dev);
        else
            run_hamming(g_flags.n,g_flags.with_1bit,g_flags.file_output, g_flags.nr_dev);
    } else if(g_flags.h_coding==2) {
        run_hamming_cpu_native_short(g_flags.n,g_flags.with_1bit,g_flags.file_output);
    } else if(g_flags.h_coding==3)
        run_hamming_cpu_native_short_ordering(g_flags.n,g_flags.with_1bit,g_flags.file_output);
    else if(g_flags.h_coding==4)
        run_hamming_cpu_native(g_flags.n,g_flags.with_1bit,g_flags.file_output);
    return 0;
}
Beispiel #18
0
int main(int argc, char *argv[])
{
  ssize_t i, j, niter;
  params_t *params;
  gk_csr_t *mat;
  FILE *fpout;
 
  /* get command-line options */
  params = parse_cmdline(argc, argv);

  /* read the data */
  mat = gk_csr_Read(params->infile, GK_CSR_FMT_METIS, 1, 1);

  /* display some basic stats */
  print_init_info(params, mat);



  if (params->ntvs != -1) {
    /* compute the pr for different randomly generated restart-distribution vectors */
    float **prs;

    prs = gk_fAllocMatrix(params->ntvs, mat->nrows, 0.0, "main: prs");

    /* generate the random restart vectors */
    for (j=0; j<params->ntvs; j++) {
      for (i=0; i<mat->nrows; i++)
        prs[j][i] = RandomInRange(931);
      gk_fscale(mat->nrows, 1.0/gk_fsum(mat->nrows, prs[j], 1), prs[j], 1);

      niter = gk_rw_PageRank(mat, params->lamda, params->eps, params->niter, prs[j]);
      printf("tvs#: %zd; niters: %zd\n", j, niter);
    }

    /* output the computed pr scores */
    fpout = gk_fopen(params->outfile, "w", "main: outfile");
    for (i=0; i<mat->nrows; i++) {
      for (j=0; j<params->ntvs; j++) 
        fprintf(fpout, "%.4e ", prs[j][i]);
      fprintf(fpout, "\n");
    }
    gk_fclose(fpout);

    gk_fFreeMatrix(&prs, params->ntvs, mat->nrows);
  }
  else if (params->ppr != -1) {
    /* compute the personalized pr from the specified vertex */
    float *pr;

    pr = gk_fsmalloc(mat->nrows, 0.0, "main: pr");

    pr[params->ppr-1] = 1.0;

    niter = gk_rw_PageRank(mat, params->lamda, params->eps, params->niter, pr);
    printf("ppr: %d; niters: %zd\n", params->ppr, niter);

    /* output the computed pr scores */
    fpout = gk_fopen(params->outfile, "w", "main: outfile");
    for (i=0; i<mat->nrows; i++) 
      fprintf(fpout, "%.4e\n", pr[i]);
    gk_fclose(fpout);

    gk_free((void **)&pr, LTERM);
  }
  else {
    /* compute the standard pr */
    int jmax;
    float diff, maxdiff;
    float *pr;

    pr = gk_fsmalloc(mat->nrows, 1.0/mat->nrows, "main: pr");

    niter = gk_rw_PageRank(mat, params->lamda, params->eps, params->niter, pr);
    printf("pr; niters: %zd\n", niter);

    /* output the computed pr scores */
    fpout = gk_fopen(params->outfile, "w", "main: outfile");
    for (i=0; i<mat->nrows; i++) {
      for (jmax=i, maxdiff=0.0, j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) {
        if ((diff = fabs(pr[i]-pr[mat->rowind[j]])) > maxdiff) {
          maxdiff = diff;
          jmax = mat->rowind[j];
        }
      }
      fprintf(fpout, "%.4e %10zd %.4e %10d\n", pr[i], 
          mat->rowptr[i+1]-mat->rowptr[i], maxdiff, jmax+1);
    }
    gk_fclose(fpout);

    gk_free((void **)&pr, LTERM);
  }

  gk_csr_Free(&mat);

  /* display some final stats */
  print_final_info(params);
}
Beispiel #19
0
int main(int argc, char **argv)
{
	int rc = 0;
	struct cfgdata_t cfg;
	struct params_t params;
	kx_inputs inputs;

	lg = log_open(16);
	log_msg(lg, "%s starting", PACKAGE_STRING);

	initmode = do_init();

	/* Get cmdline parameters */
	params.cfg = &cfg;
	init_cfgdata(&cfg);
	cfg.angle = 0;	/* No rotation by default */
	parse_cmdline(&cfg);

	kxb_ttydev = cfg.ttydev;
	setup_terminal(kxb_ttydev, &kxb_echo_state, 1);
	/* Setup function that will restore terminal when exit() will called */
	atexit(atexit_restore_terminal);

	log_msg(lg, "FB angle is %d, tty is %s", cfg.angle, cfg.ttydev);

#ifdef USE_MACHINE_KERNEL
	machine_kernel = get_machine_kernelpath();	/* FIXME should be passed as arg to get_bootinfo() */
#endif

#ifdef USE_DELAY
	/* extra delay for initializing slow SD/CF */
	sleep(USE_DELAY);
#endif

	int no_ui = 1;	/* UI presence flag */
#ifdef USE_FBMENU
	params.gui = NULL;
	if (no_ui) {
		params.gui = gui_init(cfg.angle);
		if (NULL == params.gui) {
			log_msg(lg, "Can't initialize GUI");
		} else no_ui = 0;
	}
#endif
#ifdef USE_TEXTUI
	FILE *ttyfp;
	params.tui = NULL;
	if (no_ui) {

		if (cfg.ttydev) ttyfp = fopen(cfg.ttydev, "w");
		else ttyfp = stdout;

		params.tui = tui_init(ttyfp);
		if (NULL == params.tui) {
			log_msg(lg, "Can't initialize TUI");
			if (ttyfp != stdout) fclose(ttyfp);
		} else no_ui = 0;
	}
#endif
	if (no_ui) exit(-1); /* Exit if no one UI was initialized */
	
	params.menu = build_menu(&params);
	params.bootcfg = NULL;
	scan_devices(&params);

	if (-1 == fill_menu(&params)) {
		exit(-1);
	}

	/* Collect input devices */
	inputs_init(&inputs, 8);
	inputs_open(&inputs);
	inputs_preprocess(&inputs);

	/* Run main event loop
	 * Return values: <0 - error, >=0 - selected item id */
	rc = do_main_loop(&params, &inputs);

#ifdef USE_FBMENU
	if (params.gui) {
		if (rc < 0) gui_clear(params.gui);
		gui_destroy(params.gui);
	}
#endif
#ifdef USE_TEXTUI
	if (params.tui) {
		tui_destroy(params.tui);
		if (ttyfp != stdout) fclose(ttyfp);
	}
#endif
	inputs_close(&inputs);
	inputs_clean(&inputs);

	log_close(lg);
	lg = NULL;

	/* rc < 0 indicate error */
	if (rc < 0) exit(rc);

	menu_destroy(params.menu, 0);

	if (rc >= A_DEVICES) {
		start_kernel(&params, rc - A_DEVICES);
	}

	/* When we reach this point then some error has occured */
	DPRINTF("We should not reach this point!");
	exit(-1);
}
Beispiel #20
0
static int decode(FILE *in, FILE *out) {
    struct hexfile_decoder *hfd = NULL;
    struct decoder decoder = {
        .base = 0,
        .file = out,
        .eof = 0,
        .position = 0,
    };
    char buffer[4096];
    int ret;
    size_t nbytes;

    ret = hexfile_decoder_new(hfd_callback, &decoder, &hfd);
    if (ret < 0) {
        fprintf(stderr, "failed to create hexfile decoder\n");
        _exit(2);
    }

    while ((nbytes = fread(buffer, 1, sizeof(buffer), in)) > 0) {
        ret = hexfile_decoder_feed(hfd, buffer, nbytes);
        if (ret < 0) {
            fprintf(stderr, "failed to decode hexfile\n");
            _exit(2);
        }
    }

    ret = hexfile_decoder_close(&hfd);
    if (ret < 0) {
        fprintf(stderr, "failed to close hexfile decoder\n");
        _exit(2);
    }

    if (!decoder.eof) {
        fprintf(stderr, "no EOF record\n");
        _exit(1);
    }

    return 0;
}

struct mapper {
    unsigned base, start, end;
    FILE *file;
    int eof;
};

static void map_print(const struct mapper *mapper) {
    if (mapper->end > mapper->start)
        fprintf(mapper->file, "0x%08x-0x%08x\n", mapper->start, mapper->end);
}

static int map_callback(void *ctx,
                        unsigned char type, unsigned offset,
                        unsigned char *data, size_t length) {
    struct mapper *mapper = (struct mapper*)ctx;

    (void)data;

    if (mapper->eof) {
        errno = EINVAL;
        return -1;
    }

    if (type == 0x00) {
        /* data record */
        unsigned new_position, new_end;

        new_position = (mapper->base + offset) & ~0xf;
        new_end = (new_position + length) | 0xf;

        if (new_position < mapper->start || new_position > mapper->end + 1) {
            map_print(mapper);
            mapper->start = new_position;
            mapper->end = new_end;
        } else if (new_end > mapper->end) {
            mapper->end = new_end;
        }

        return 0;
    } else if (type == 0x01) {
        /* EOF record */
        mapper->eof = 1;
        return 0;
    } else if (type >= 0x10) {
        /* switch memory bank */
        unsigned new_base = (type - 0x10) * BANK_SIZE;

        if (mapper->end != new_base) {
            map_print(mapper);
            mapper->start = mapper->end = new_base;
        }

        mapper->base = new_base;
        return 0;
    } else {
        errno = ENOSYS;
        return -1;
    }
}

static int map(FILE *in, FILE *out) {
    struct hexfile_decoder *hfd = NULL;
    struct mapper mapper = {
        .base = 0,
        .start = 0,
        .end = 0,
        .file = out,
        .eof = 0,
    };
    char buffer[4096];
    int ret;
    size_t nbytes;

    ret = hexfile_decoder_new(map_callback, &mapper, &hfd);
    if (ret < 0) {
        fprintf(stderr, "failed to create hexfile decoder\n");
        _exit(2);
    }

    while ((nbytes = fread(buffer, 1, sizeof(buffer), in)) > 0) {
        ret = hexfile_decoder_feed(hfd, buffer, nbytes);
        if (ret < 0) {
            fprintf(stderr, "failed to decode hexfile\n");
            _exit(2);
        }
    }

    ret = hexfile_decoder_close(&hfd);
    if (ret < 0) {
        fprintf(stderr, "failed to close hexfile decoder\n");
        _exit(2);
    }

    if (!mapper.eof) {
        fprintf(stderr, "no EOF record\n");
        _exit(1);
    }

    return 0;
}

int main(int argc, char **argv) {
    struct config config;
    FILE *in, *out;

    parse_cmdline(&config, argc, argv);

    if (config.input_path == NULL) {
        in = stdin;
    } else {
        in = fopen(argv[optind], "r");
        if (in == NULL) {
            fprintf(stderr, "failed to open '%s': %s",
                    argv[optind], strerror(errno));
            _exit(1);
        }
    }

    if (config.output_path == NULL) {
        out = stdout;
    } else {
        out = fopen(config.output_path, "w");
        if (out == NULL) {
            fprintf(stderr, "failed to create '%s': %s\n",
                    config.output_path, strerror(errno));
            _exit(1);
        }
    }

    /* do it */
    if (config.decode) {
        return decode(in, out);
    } else if (config.map) {
        return map(in, out);
    } else {
        return encode(in, out);
    }
}
Beispiel #21
0
int mpd_main(int argc, char *argv[])
{
	struct options options;
	clock_t start;
	bool create_db;
	GError *error = NULL;
	bool success;

	daemonize_close_stdin();

#ifdef HAVE_LOCALE_H
	/* initialize locale */
	setlocale(LC_CTYPE,"");
#endif

	g_set_application_name("Music Player Daemon");

	/* enable GLib's thread safety code */
	g_thread_init(NULL);

	io_thread_init();
	winsock_init();
	idle_init();
	tag_pool_init();
	config_global_init();

	success = parse_cmdline(argc, argv, &options, &error);
	if (!success) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	if (!glue_daemonize_init(&options, &error)) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	stats_global_init();
	tag_lib_init();

	if (!log_init(options.verbose, options.log_stderr, &error)) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	success = listen_global_init(&error);
	if (!success) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	daemonize_set_user();

	main_task = g_thread_self();
	main_loop = g_main_loop_new(NULL, FALSE);
	main_cond = g_cond_new();

	event_pipe_init();
	event_pipe_register(PIPE_EVENT_IDLE, idle_event_emitted);
	event_pipe_register(PIPE_EVENT_SHUTDOWN, shutdown_event_emitted);

	path_global_init();

	if (!glue_mapper_init(&error)) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	initPermissions();
	playlist_global_init();
	spl_global_init();
#ifdef ENABLE_ARCHIVE
	archive_plugin_init_all();
#endif

	if (!pcm_resample_global_init(&error)) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	decoder_plugin_init_all();
	update_global_init();

	create_db = !glue_db_init_and_load();

	glue_sticker_init();

	command_init();
	initialize_decoder_and_player();
	volume_init();
	initAudioConfig();
	audio_output_all_init(global_player_control);
	client_manager_init();
	replay_gain_global_init();

	if (!input_stream_global_init(&error)) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	playlist_list_global_init();

	daemonize(options.daemon);

	setup_log_output(options.log_stderr);

	initSigHandlers();

	if (!io_thread_start(&error)) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	initZeroconf();

	player_create(global_player_control);

	if (create_db) {
		/* the database failed to load: recreate the
		   database */
		unsigned job = update_enqueue(NULL, true);
		if (job == 0)
			MPD_ERROR("directory update failed");
	}

	if (!glue_state_file_init(&error)) {
		g_warning("%s", error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}

	success = config_get_bool(CONF_AUTO_UPDATE, false);
#ifdef ENABLE_INOTIFY
	if (success && mapper_has_music_directory())
		mpd_inotify_init(config_get_unsigned(CONF_AUTO_UPDATE_DEPTH,
						     G_MAXUINT));
#else
	if (success)
		g_warning("inotify: auto_update was disabled. enable during compilation phase");
#endif

	config_global_check();

	/* enable all audio outputs (if not already done by
	   playlist_state_restore() */
	pc_update_audio(global_player_control);

#ifdef WIN32
	win32_app_started();
#endif

	/* run the main loop */
	g_main_loop_run(main_loop);

#ifdef WIN32
	win32_app_stopping();
#endif

	/* cleanup */

	g_main_loop_unref(main_loop);

#ifdef ENABLE_INOTIFY
	mpd_inotify_finish();
#endif

	state_file_finish(global_player_control);
	pc_kill(global_player_control);
	finishZeroconf();
	client_manager_deinit();
	listen_global_finish();
	playlist_global_finish();

	start = clock();
	db_finish();
	g_debug("db_finish took %f seconds",
		((float)(clock()-start))/CLOCKS_PER_SEC);

#ifdef ENABLE_SQLITE
	sticker_global_finish();
#endif

	g_cond_free(main_cond);
	event_pipe_deinit();

	playlist_list_global_finish();
	input_stream_global_finish();
	audio_output_all_finish();
	volume_finish();
	mapper_finish();
	path_global_finish();
	finishPermissions();
	pc_free(global_player_control);
	command_finish();
	update_global_finish();
	decoder_plugin_deinit_all();
#ifdef ENABLE_ARCHIVE
	archive_plugin_deinit_all();
#endif
	config_global_finish();
	tag_pool_deinit();
	idle_deinit();
	stats_global_finish();
	io_thread_deinit();
	daemonize_finish();
#ifdef WIN32
	WSACleanup();
#endif

	log_deinit();
	return EXIT_SUCCESS;
}
int
main(int argc, char **argv)
{
        // Standard command line parsing.
        HASH_T *options = parse_cmdline(argc, argv, arg_opts);
        if(options == NULL || hash_get(options, "help") != NULL) {
                show_usage(argc, argv, arg_opts);
                return 1;
        }

        char *url = hash_get(options, "url");

        const char *principal = hash_get(options, "principal");
        CREDENTIALS_T *credentials = NULL;

        const char *password = hash_get(options, "credentials");
        if(password != NULL) {
                credentials = credentials_create_password(password);
        }

        char *topic = hash_get(options, "topic");
        char *session_id_str = hash_get(options, "session_id");

        // Setup for condition variable.
        apr_initialize();
        apr_pool_create(&pool, NULL);
        apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_UNNESTED, pool);
        apr_thread_cond_create(&cond, pool);

        // Create a session with Diffusion.
        SESSION_T *session = NULL;
        DIFFUSION_ERROR_T error;
        session = session_create(url, principal, credentials, NULL, NULL, &error);
        if(session == NULL) {
                fprintf(stderr, "TEST: Failed to create session\n");
                fprintf(stderr, "ERR : %s\n", error.message);
                return 1;
        }

        // Create a payload.
        char *data = hash_get(options, "data");
        BUF_T *payload = buf_create();
        buf_write_bytes(payload, data, strlen(data));
        CONTENT_T *content = content_create(CONTENT_ENCODING_NONE, payload);
        buf_free(payload);

        // Build up some headers to send with the message.
        LIST_T *headers = list_create();
        list_append_last(headers, "apple");
        list_append_last(headers, "train");

        // Parameters for send_msg_to_session() call.
        SESSION_ID_T *session_id = session_id_create_from_string(session_id_str);

        SEND_MSG_TO_SESSION_PARAMS_T params = {
                .topic_path = topic,
                .session_id = *session_id,
                .content = *content,
                .options.headers = headers,
                .options.priority = CLIENT_SEND_PRIORITY_NORMAL,
                .on_send = on_send,
                .context = "FOO"
        };

        // Send the message and wait for the callback to acknowledge delivery.
        apr_thread_mutex_lock(mutex);
        send_msg_to_session(session, params);
        apr_thread_cond_wait(cond, mutex);
        apr_thread_mutex_unlock(mutex);

        // Politely close the client connection.
        session_id_free(session_id);
        session_close(session, &error);

        return 0;
}
Beispiel #23
0
/**
 * main
 */
int main(int argc, const char **argv)
{
   // Our main data storage vessel..
   RASPISTILLYUV_STATE state;
   int exit_code = EX_OK;

   MMAL_STATUS_T status = MMAL_SUCCESS;
   MMAL_PORT_T *camera_preview_port = NULL;
   MMAL_PORT_T *camera_video_port = NULL;
   MMAL_PORT_T *camera_still_port = NULL;
   MMAL_PORT_T *preview_input_port = NULL;
   FILE *output_file = NULL;

   bcm_host_init();

   // Register our application with the logging system
   vcos_log_register("RaspiStill", VCOS_LOG_CATEGORY);

   signal(SIGINT, signal_handler);

   // Disable USR1 for the moment - may be reenabled if go in to signal capture mode
   signal(SIGUSR1, SIG_IGN);

   default_status(&state);

   // Do we have any parameters
   if (argc == 1)
   {
      fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);

      display_valid_parameters(basename(argv[0]));
      exit(EX_USAGE);
   }

   default_status(&state);

   // Parse the command line and put options in to our status structure
   if (parse_cmdline(argc, argv, &state))
   {
      status = -1;
      exit(EX_USAGE);
   }

   if (state.verbose)
   {
      fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);
      dump_status(&state);
   }

   // OK, we have a nice set of parameters. Now set up our components
   // We have two components. Camera and Preview
   // Camera is different in stills/video, but preview
   // is the same so handed off to a separate module

   if ((status = create_camera_component(&state)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create camera component", __func__);
      exit_code = EX_SOFTWARE;
   }
   else if ((status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);
      exit_code = EX_SOFTWARE;
   }
   else
   {
      PORT_USERDATA callback_data;

      if (state.verbose)
         fprintf(stderr, "Starting component connection stage\n");

      camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];

      // Note we are lucky that the preview and null sink components use the same input port
      // so we can simple do this without conditionals
      preview_input_port  = state.preview_parameters.preview_component->input[0];

      // Connect camera to preview (which might be a null_sink if no preview required)
      status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);

      if (status == MMAL_SUCCESS)
      {
         VCOS_STATUS_T vcos_status;

         // Set up our userdata - this is passed though to the callback where we need the information.
         // Null until we open our filename
         callback_data.file_handle = NULL;
         callback_data.pstate = &state;

         vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
         vcos_assert(vcos_status == VCOS_SUCCESS);

         camera_still_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

         if (state.verbose)
            fprintf(stderr, "Enabling camera still output port\n");

         // Enable the camera still output port and tell it its callback function
         status = mmal_port_enable(camera_still_port, camera_buffer_callback);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("Failed to setup camera output");
            goto error;
         }

         if (state.verbose)
            fprintf(stderr, "Starting video preview\n");


         int frame, keep_looping = 1;
         FILE *output_file = NULL;
         char *use_filename = NULL;      // Temporary filename while image being written
         char *final_filename = NULL;    // Name that file gets once writing complete

         frame = 0;

         while (keep_looping)
         {
             keep_looping = wait_for_next_frame(&state, &frame);

            // Open the file
            if (state.filename)
            {
               if (state.filename[0] == '-')
               {
                  output_file = stdout;

                  // Ensure we don't upset the output stream with diagnostics/info
                  state.verbose = 0;
               }
               else
               {
                  vcos_assert(use_filename == NULL && final_filename == NULL);
                  status = create_filenames(&final_filename, &use_filename, state.filename, frame);
                  if (status  != MMAL_SUCCESS)
                  {
                     vcos_log_error("Unable to create filenames");
                     goto error;
                  }

                  if (state.verbose)
                     fprintf(stderr, "Opening output file %s\n", final_filename);
                     // Technically it is opening the temp~ filename which will be ranamed to the final filename

                  output_file = fopen(use_filename, "wb");

                  if (!output_file)
                  {
                     // Notify user, carry on but discarding encoded output buffers
                     vcos_log_error("%s: Error opening output file: %s\nNo output file will be generated\n", __func__, use_filename);
                  }
               }

               callback_data.file_handle = output_file;
            }

            if (output_file)
            {
               int num, q;

               // There is a possibility that shutter needs to be set each loop.
               if (mmal_status_to_int(mmal_port_parameter_set_uint32(state.camera_component->control, MMAL_PARAMETER_SHUTTER_SPEED, state.camera_parameters.shutter_speed) != MMAL_SUCCESS))
                  vcos_log_error("Unable to set shutter speed");


               // Send all the buffers to the camera output port
               num = mmal_queue_length(state.camera_pool->queue);

               for (q=0;q<num;q++)
               {
                  MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.camera_pool->queue);

                  if (!buffer)
                     vcos_log_error("Unable to get a required buffer %d from pool queue", q);

                  if (mmal_port_send_buffer(camera_still_port, buffer)!= MMAL_SUCCESS)
                     vcos_log_error("Unable to send a buffer to camera output port (%d)", q);
               }

               if (state.burstCaptureMode && frame==1)
               {
                  mmal_port_parameter_set_boolean(state.camera_component->control,  MMAL_PARAMETER_CAMERA_BURST_CAPTURE, 1);
               }

               if (state.verbose)
                  fprintf(stderr, "Starting capture %d\n", frame);

               if (mmal_port_parameter_set_boolean(camera_still_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
               {
                  vcos_log_error("%s: Failed to start capture", __func__);
               }
               else
               {
                  // Wait for capture to complete
                  // For some reason using vcos_semaphore_wait_timeout sometimes returns immediately with bad parameter error
                  // even though it appears to be all correct, so reverting to untimed one until figure out why its erratic
                  vcos_semaphore_wait(&callback_data.complete_semaphore);
                  if (state.verbose)
                     fprintf(stderr, "Finished capture %d\n", frame);
               }

               // Ensure we don't die if get callback with no open file
               callback_data.file_handle = NULL;

               if (output_file != stdout)
               {
                  rename_file(&state, output_file, final_filename, use_filename, frame);
               }
            }

            if (use_filename)
            {
               free(use_filename);
               use_filename = NULL;
            }
            if (final_filename)
            {
               free(final_filename);
               final_filename = NULL;
            }
         } // end for (frame)
         
         vcos_semaphore_delete(&callback_data.complete_semaphore);
      }
      else
      {
         mmal_status_to_int(status);
         vcos_log_error("%s: Failed to connect camera to preview", __func__);
      }

error:

      mmal_status_to_int(status);

      if (state.verbose)
         fprintf(stderr, "Closing down\n");

      if (output_file)
         fclose(output_file);

      // Disable all our ports that are not handled by connections
      check_disable_port(camera_video_port);

      if (state.preview_connection)
         mmal_connection_destroy(state.preview_connection);

      /* Disable components */
      if (state.preview_parameters.preview_component)
         mmal_component_disable(state.preview_parameters.preview_component);

      if (state.camera_component)
         mmal_component_disable(state.camera_component);

      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);

      if (state.verbose)
         fprintf(stderr, "Close down completed, all components disconnected, disabled and destroyed\n\n");
   }

   if (status != MMAL_SUCCESS)
      raspicamcontrol_check_configuration(128);

   return exit_code;
}
Beispiel #24
0
int main(int argc, char **argp, char **envp)
{
	parse_cmdline(argc, argp);
	return doit();
}
Beispiel #25
0
int glp_main(int argc, const char *argv[])
{     /* stand-alone LP/MIP solver */
      struct csa _csa, *csa = &_csa;
      int ret;
      xlong_t start;
      /* perform initialization */
      csa->prob = glp_create_prob();
      glp_get_bfcp(csa->prob, &csa->bfcp);
      glp_init_smcp(&csa->smcp);
      csa->smcp.presolve = GLP_ON;
      glp_init_iocp(&csa->iocp);
      csa->iocp.presolve = GLP_ON;
      csa->tran = NULL;
      csa->graph = NULL;
      csa->format = FMT_MPS_FILE;
      csa->in_file = NULL;
      csa->ndf = 0;
      csa->out_dpy = NULL;
      csa->solution = SOL_BASIC;
      csa->in_res = NULL;
      csa->dir = 0;
      csa->scale = 1;
      csa->out_sol = NULL;
      csa->out_res = NULL;
      csa->out_bnds = NULL;
      csa->check = 0;
      csa->new_name = NULL;
      csa->out_mps = NULL;
      csa->out_freemps = NULL;
      csa->out_cpxlp = NULL;
      csa->out_pb = NULL;
      csa->out_npb = NULL;
      csa->log_file = NULL;
      csa->crash = USE_ADV_BASIS;
      csa->exact = 0;
      csa->xcheck = 0;
      csa->nomip = 0;
      /* parse command-line parameters */
      ret = parse_cmdline(csa, argc, argv);
      if (ret < 0)
      {  ret = EXIT_SUCCESS;
         goto done;
      }
      if (ret > 0)
      {  ret = EXIT_FAILURE;
         goto done;
      }
      /*--------------------------------------------------------------*/
      /* remove all output files specified in the command line */
      if (csa->out_dpy != NULL) remove(csa->out_dpy);
      if (csa->out_sol != NULL) remove(csa->out_sol);
      if (csa->out_res != NULL) remove(csa->out_res);
      if (csa->out_bnds != NULL) remove(csa->out_bnds);
      if (csa->out_mps != NULL) remove(csa->out_mps);
      if (csa->out_freemps != NULL) remove(csa->out_freemps);
      if (csa->out_cpxlp != NULL) remove(csa->out_cpxlp);
      if (csa->out_pb != NULL) remove(csa->out_pb);
      if (csa->out_npb != NULL) remove(csa->out_npb);
      if (csa->log_file != NULL) remove(csa->log_file);
      /*--------------------------------------------------------------*/
      /* open log file, if required */
      if (csa->log_file != NULL)
      {  if (lib_open_log(csa->log_file))
         {  xprintf("Unable to create log file\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* read problem data from the input file */
      if (csa->in_file == NULL)
      {  xprintf("No input problem file specified; try %s --help\n",
            argv[0]);
         ret = EXIT_FAILURE;
         goto done;
      }
      if (csa->format == FMT_MPS_DECK)
      {  ret = glp_read_mps(csa->prob, GLP_MPS_DECK, NULL,
            csa->in_file);
         if (ret != 0)
err1:    {  xprintf("MPS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      else if (csa->format == FMT_MPS_FILE)
      {  ret = glp_read_mps(csa->prob, GLP_MPS_FILE, NULL,
            csa->in_file);
         if (ret != 0) goto err1;
      }
      else if (csa->format == FMT_CPLEX_LP)
      {  ret = glp_read_lp(csa->prob, NULL, csa->in_file);
         if (ret != 0)
         {  xprintf("CPLEX LP file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      else if (csa->format == FMT_MATHPROG)
      {  int k;
         /* allocate the translator workspace */
         csa->tran = glp_mpl_alloc_wksp();
         /* read model section and optional data section */
         if (glp_mpl_read_model(csa->tran, csa->in_file, csa->ndf > 0))
err2:    {  xprintf("MathProg model processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         /* read optional data section(s), if necessary */
         for (k = 1; k <= csa->ndf; k++)
         {  if (glp_mpl_read_data(csa->tran, csa->in_data[k]))
               goto err2;
         }
         /* generate the model */
         if (glp_mpl_generate(csa->tran, csa->out_dpy)) goto err2;
         /* build the problem instance from the model */
         glp_mpl_build_prob(csa->tran, csa->prob);
      }
      else if (csa->format == FMT_MIN_COST)
      {  csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data));
         ret = glp_read_mincost(csa->graph, offsetof(v_data, rhs),
            offsetof(a_data, low), offsetof(a_data, cap),
            offsetof(a_data, cost), csa->in_file);
         if (ret != 0)
         {  xprintf("DIMACS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         glp_mincost_lp(csa->prob, csa->graph, GLP_ON,
            offsetof(v_data, rhs), offsetof(a_data, low),
            offsetof(a_data, cap), offsetof(a_data, cost));
         glp_set_prob_name(csa->prob, csa->in_file);
      }
      else if (csa->format == FMT_MAX_FLOW)
      {  int s, t;
         csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data));
         ret = glp_read_maxflow(csa->graph, &s, &t,
            offsetof(a_data, cap), csa->in_file);
         if (ret != 0)
         {  xprintf("DIMACS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         glp_maxflow_lp(csa->prob, csa->graph, GLP_ON, s, t,
            offsetof(a_data, cap));
         glp_set_prob_name(csa->prob, csa->in_file);
      }
      else
         xassert(csa != csa);
      /*--------------------------------------------------------------*/
      /* change problem name, if required */
      if (csa->new_name != NULL)
         glp_set_prob_name(csa->prob, csa->new_name);
      /* change optimization direction, if required */
      if (csa->dir != 0)
         glp_set_obj_dir(csa->prob, csa->dir);
      /* order rows and columns of the constraint matrix */
      lpx_order_matrix(csa->prob);
      /*--------------------------------------------------------------*/
      /* write problem data in fixed MPS format, if required */
      if (csa->out_mps != NULL)
      {  ret = glp_write_mps(csa->prob, GLP_MPS_DECK, NULL,
            csa->out_mps);
         if (ret != 0)
         {  xprintf("Unable to write problem in fixed MPS format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in free MPS format, if required */
      if (csa->out_freemps != NULL)
      {  ret = glp_write_mps(csa->prob, GLP_MPS_FILE, NULL,
            csa->out_freemps);
         if (ret != 0)
         {  xprintf("Unable to write problem in free MPS format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in CPLEX LP format, if required */
      if (csa->out_cpxlp != NULL)
      {  ret = glp_write_lp(csa->prob, NULL, csa->out_cpxlp);
         if (ret != 0)
         {  xprintf("Unable to write problem in CPLEX LP format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in OPB format, if required */
      if (csa->out_pb != NULL)
      {  ret = lpx_write_pb(csa->prob, csa->out_pb, 0, 0);
         if (ret != 0)
         {  xprintf("Unable to write problem in OPB format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in normalized OPB format, if required */
      if (csa->out_npb != NULL)
      {  ret = lpx_write_pb(csa->prob, csa->out_npb, 1, 1);
         if (ret != 0)
         {  xprintf(
               "Unable to write problem in normalized OPB format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* if only problem data check is required, skip computations */
      if (csa->check)
      {  ret = EXIT_SUCCESS;
         goto done;
      }
      /*--------------------------------------------------------------*/
      /* determine the solution type */
      if (!csa->nomip &&
          glp_get_num_int(csa->prob) + glp_get_num_bin(csa->prob) > 0)
      {  if (csa->solution == SOL_INTERIOR)
         {  xprintf("Interior-point method is not able to solve MIP pro"
               "blem; use --simplex\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         csa->solution = SOL_INTEGER;
      }
      /*--------------------------------------------------------------*/
      /* if solution is provided, read it and skip computations */
      if (csa->in_res != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_read_sol(csa->prob, csa->in_res);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_read_ipt(csa->prob, csa->in_res);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_read_mip(csa->prob, csa->in_res);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to read problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         goto skip;
      }
      /*--------------------------------------------------------------*/
      /* scale the problem data, if required */
      if (csa->scale)
      {  if (csa->solution == SOL_BASIC && !csa->smcp.presolve ||
             csa->solution == SOL_INTERIOR ||
             csa->solution == SOL_INTEGER && !csa->iocp.presolve)
            glp_scale_prob(csa->prob, GLP_SF_AUTO);
      }
      /* construct starting LP basis */
      if (csa->solution == SOL_BASIC && !csa->smcp.presolve ||
          csa->solution == SOL_INTEGER && !csa->iocp.presolve)
      {  if (csa->crash == USE_STD_BASIS)
            glp_std_basis(csa->prob);
         else if (csa->crash == USE_ADV_BASIS)
            glp_adv_basis(csa->prob, 0);
         else if (csa->crash == USE_CPX_BASIS)
            glp_cpx_basis(csa->prob);
         else
            xassert(csa != csa);
      }
      /*--------------------------------------------------------------*/
      /* solve the problem */
      start = xtime();
      if (csa->solution == SOL_BASIC)
      {  if (!csa->exact)
         {  glp_set_bfcp(csa->prob, &csa->bfcp);
            glp_simplex(csa->prob, &csa->smcp);
            if (csa->xcheck)
            {  if (csa->smcp.presolve &&
                   glp_get_status(csa->prob) != GLP_OPT)
                  xprintf("If you need to check final basis for non-opt"
                     "imal solution, use --nopresol\n");
               else
                  glp_exact(csa->prob, &csa->smcp);
            }
            if (csa->out_sol != NULL || csa->out_res != NULL)
            {  if (csa->smcp.presolve &&
                   glp_get_status(csa->prob) != GLP_OPT)
               xprintf("If you need actual output for non-optimal solut"
                  "ion, use --nopresol\n");
            }
         }
         else
            glp_exact(csa->prob, &csa->smcp);
      }
      else if (csa->solution == SOL_INTERIOR)
         glp_interior(csa->prob, NULL);
      else if (csa->solution == SOL_INTEGER)
      {  if (!csa->iocp.presolve)
         {  glp_set_bfcp(csa->prob, &csa->bfcp);
            glp_simplex(csa->prob, &csa->smcp);
         }
         glp_intopt(csa->prob, &csa->iocp);
      }
      else
         xassert(csa != csa);
      /*--------------------------------------------------------------*/
      /* display statistics */
      xprintf("Time used:   %.1f secs\n", xdifftime(xtime(), start));
      {  xlong_t tpeak;
         char buf[50];
         lib_mem_usage(NULL, NULL, NULL, &tpeak);
         xprintf("Memory used: %.1f Mb (%s bytes)\n",
            xltod(tpeak) / 1048576.0, xltoa(tpeak, buf));
      }
      /*--------------------------------------------------------------*/
skip: /* postsolve the model, if necessary */
      if (csa->tran != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_SOL);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_IPT);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_MIP);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Model postsolving error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* write problem solution in printable format, if required */
      if (csa->out_sol != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = lpx_print_sol(csa->prob, csa->out_sol);
         else if (csa->solution == SOL_INTERIOR)
            ret = lpx_print_ips(csa->prob, csa->out_sol);
         else if (csa->solution == SOL_INTEGER)
            ret = lpx_print_mip(csa->prob, csa->out_sol);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to write problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem solution in printable format, if required */
      if (csa->out_res != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_write_sol(csa->prob, csa->out_res);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_write_ipt(csa->prob, csa->out_res);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_write_mip(csa->prob, csa->out_res);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to write problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write sensitivity bounds information, if required */
      if (csa->out_bnds != NULL)
      {  if (csa->solution == SOL_BASIC)
         {  ret = lpx_print_sens_bnds(csa->prob, csa->out_bnds);
            if (ret != 0)
            {  xprintf("Unable to write sensitivity bounds information "
                  "\n");
               ret = EXIT_FAILURE;
               goto done;
            }
         }
         else
            xprintf("Cannot write sensitivity bounds information for in"
               "terior-point or MIP solution\n");
      }
      /*--------------------------------------------------------------*/
      /* all seems to be ok */
      ret = EXIT_SUCCESS;
      /*--------------------------------------------------------------*/
done: /* delete the LP/MIP problem object */
      if (csa->prob != NULL)
         glp_delete_prob(csa->prob);
      /* free the translator workspace, if necessary */
      if (csa->tran != NULL)
         glp_mpl_free_wksp(csa->tran);
      /* delete the network problem object, if necessary */
      if (csa->graph != NULL)
         glp_delete_graph(csa->graph);
      xassert(gmp_pool_count() == 0);
      gmp_free_mem();
      /* close log file, if necessary */
      if (csa->log_file != NULL) lib_close_log();
      /* check that no memory blocks are still allocated */
      {  int count;
         xlong_t total;
         lib_mem_usage(&count, NULL, &total, NULL);
         if (count != 0)
            xerror("Error: %d memory block(s) were lost\n", count);
         xassert(count == 0);
         xassert(total.lo == 0 && total.hi == 0);
      }
      /* free the library environment */
      lib_free_env();
      /* return to the control program */
      return ret;
}
Beispiel #26
0
int main(int argc, char** argv)
{
	int parseres = parse_cmdline(argc, argv);
	int i, readres, writeres;
	int only_clock_queries;
	struct cpu_raw_data_t raw;
	struct cpu_id_t data;

	if (parseres != 1)
		return parseres;

	/* In quiet mode, disable libcpuid warning messages: */
	if (need_quiet)
		cpuid_set_warn_function(NULL);
	
	cpuid_set_verbosiness_level(verbose_level);

	/* Redirect output, if necessary: */
	if (strcmp(out_file, "") && strcmp(out_file, "-")) {
		fout = fopen(out_file, "wt");
		if (!fout) {
			if (!need_quiet)
				fprintf(stderr, "Cannot open `%s' for writing!\n", out_file);
			return -1;
		}
		atexit(close_out);
	} else {
		fout = stdout;
	}
	
	/* If requested, print library version: */
	if (need_version)
		fprintf(fout, "%s\n", cpuid_lib_version());
	
	if (need_input) {
		/* We have a request to input raw CPUID data from file: */
		if (!strcmp(raw_data_file, "-"))
			/* Input from stdin */
			readres = cpuid_deserialize_raw_data(&raw, "");
		else
			/* Input from file */
			readres = cpuid_deserialize_raw_data(&raw, raw_data_file);
		if (readres < 0) {
			if (!need_quiet) {
				fprintf(stderr, "Cannot deserialize raw data from ");
				if (!strcmp(raw_data_file, "-"))
					fprintf(stderr, "stdin\n");
				else
					fprintf(stderr, "file `%s'\n", raw_data_file);
				/* Print the error message */
				fprintf(stderr, "Error: %s\n", cpuid_error());
			}
			return -1;
		}
	} else {
		if (check_need_raw_data()) {
			/* Try to obtain raw CPUID data from the CPU: */
			readres = cpuid_get_raw_data(&raw);
			if (readres < 0) {
				if (!need_quiet) {
					fprintf(stderr, "Cannot obtain raw CPU data!\n");
					fprintf(stderr, "Error: %s\n", cpuid_error());
				}
				return -1;
			}
		}
	}
	
	/* Need to dump raw CPUID data to file: */
	if (need_output) {
		if (verbose_level >= 1)
			printf("Writing raw CPUID dump to `%s'\n", raw_data_file);
		if (!strcmp(raw_data_file, "-"))
			/* Serialize to stdout */
			writeres = cpuid_serialize_raw_data(&raw, "");
		else
			/* Serialize to file */
			writeres = cpuid_serialize_raw_data(&raw, raw_data_file);
		if (writeres < 0) {
			if (!need_quiet) {
				fprintf(stderr, "Cannot serialize raw data to ");
				if (!strcmp(raw_data_file, "-"))
					fprintf(stderr, "stdout\n");
				else
					fprintf(stderr, "file `%s'\n", raw_data_file);
				/* Print the error message */
				fprintf(stderr, "Error: %s\n", cpuid_error());
			}
			return -1;
		}
	}
	if (need_report) {
		if (verbose_level >= 1) {
			printf("Writing decoded CPU report to `%s'\n", out_file);
		}
		/* Write a thorough report of cpu_id_t structure to output (usually stdout) */
		fprintf(fout, "CPUID is present\n");
		/*
		 * Try CPU identification
		 * (this fill the `data' structure with decoded CPU features)
		 */
		if (cpu_identify(&raw, &data) < 0)
			fprintf(fout, "Error identifying the CPU: %s\n", cpuid_error());
		
		/* OK, now write what we have in `data'...: */
		fprintf(fout, "CPU Info:\n------------------\n");
		fprintf(fout, "  vendor_str : `%s'\n", data.vendor_str);
		fprintf(fout, "  vendor id  : %d\n", (int) data.vendor);
		fprintf(fout, "  brand_str  : `%s'\n", data.brand_str);
		fprintf(fout, "  family     : %d (%02Xh)\n", data.family, data.family);
		fprintf(fout, "  model      : %d (%02Xh)\n", data.model, data.model);
		fprintf(fout, "  stepping   : %d (%02Xh)\n", data.stepping, data.stepping);
		fprintf(fout, "  ext_family : %d (%02Xh)\n", data.ext_family, data.ext_family);
		fprintf(fout, "  ext_model  : %d (%02Xh)\n", data.ext_model, data.ext_model);
		fprintf(fout, "  num_cores  : %d\n", data.num_cores);
		fprintf(fout, "  num_logical: %d\n", data.num_logical_cpus);
		fprintf(fout, "  tot_logical: %d\n", data.total_logical_cpus);
		fprintf(fout, "  L1 D cache : %d KB\n", data.l1_data_cache);
		fprintf(fout, "  L1 I cache : %d KB\n", data.l1_instruction_cache);
		fprintf(fout, "  L2 cache   : %d KB\n", data.l2_cache);
		fprintf(fout, "  L3 cache   : %d KB\n", data.l3_cache);
		fprintf(fout, "  L4 cache   : %d KB\n", data.l4_cache);
		fprintf(fout, "  L1D assoc. : %d-way\n", data.l1_assoc);
		fprintf(fout, "  L2 assoc.  : %d-way\n", data.l2_assoc);
		fprintf(fout, "  L3 assoc.  : %d-way\n", data.l3_assoc);
		fprintf(fout, "  L4 assoc.  : %d-way\n", data.l4_assoc);
		fprintf(fout, "  L1D line sz: %d bytes\n", data.l1_cacheline);
		fprintf(fout, "  L2 line sz : %d bytes\n", data.l2_cacheline);
		fprintf(fout, "  L3 line sz : %d bytes\n", data.l3_cacheline);
		fprintf(fout, "  L4 line sz : %d bytes\n", data.l4_cacheline);
		fprintf(fout, "  SSE units  : %d bits (%s)\n", data.sse_size, data.detection_hints[CPU_HINT_SSE_SIZE_AUTH] ? "authoritative" : "non-authoritative");
		fprintf(fout, "  code name  : `%s'\n", data.cpu_codename);
		fprintf(fout, "  features   :");
		/*
		 * Here we enumerate all CPU feature bits, and when a feature
		 * is present output its name:
		 */
		for (i = 0; i < NUM_CPU_FEATURES; i++)
			if (data.flags[i])
				fprintf(fout, " %s", cpu_feature_str(i));
		fprintf(fout, "\n");
		
		/* Is CPU clock info requested? */
		if (need_clockreport) {
			if (need_timed_clockreport) {
				/* Here we use the RDTSC-based routine */
				fprintf(fout, "  cpu clock  : %d MHz\n",
				        cpu_clock_measure(400, 1));
			} else {
				/* Here we use the OS-provided info */
				fprintf(fout, "  cpu clock  : %d MHz\n",
				        cpu_clock());
			}
		}
	}
	/*
	 * Check if we have any queries to process.
	 * We have to handle the case when `--clock' or `--clock-rdtsc' options
	 * are present.
	 * If in report mode, this will generate spurious output after the
	 * report, if not handled explicitly.
	 */
	only_clock_queries = 1;
	for (i = 0; i < num_requests; i++)
		if (requests[i] != NEED_CLOCK && requests[i] != NEED_CLOCK_RDTSC) {
			only_clock_queries = 0;
			break;
		}
	/* OK, process all queries. */
	if (((!need_report || !only_clock_queries) && num_requests > 0) || need_identify) {
		/* Identify the CPU. Make it do cpuid_get_raw_data() itself */
		if (check_need_raw_data() && cpu_identify(&raw, &data) < 0) {
			if (!need_quiet)
				fprintf(stderr,
				        "Error identifying the CPU: %s\n",
				        cpuid_error());
			return -1;
		}
		for (i = 0; i < num_requests; i++)
			print_info(requests[i], &raw, &data);
	}
	if (need_cpulist) {
		print_cpulist();
	}
	if (need_sgx) {
		print_sgx_data(&raw, &data);
	}
	
	return 0;
}
Beispiel #27
0
int main(int argc, char * const argv[])
{
	int r, c, long_optind = 0, err = 0;
	char *line;
	int cargc;
	char *cargv[260];
	sc_context_param_t ctx_param;
	int lcycle = SC_CARDCTRL_LIFECYCLE_ADMIN;
	FILE *script = stdin;

	printf("OpenSC Explorer version %s\n", sc_get_version());

	while (1) {
		c = getopt_long(argc, argv, "r:c:vwm:", options, &long_optind);
		if (c == -1)
			break;
		if (c == '?')
			util_print_usage_and_die(app_name, options, option_help, "[SCRIPT]");
		switch (c) {
		case 'r':
			opt_reader = optarg;
			break;
		case 'c':
			opt_driver = optarg;
			break;
		case 'w':
			opt_wait = 1;
			break;
		case 'v':
			verbose++;
			break;
		case 'm':
			opt_startfile = optarg;
			break;
		}
	}

	memset(&ctx_param, 0, sizeof(ctx_param));
	ctx_param.ver      = 0;
	ctx_param.app_name = app_name;

	r = sc_context_create(&ctx, &ctx_param);
	if (r) {
		fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
		return 1;
	}

	ctx->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER;

	if (verbose > 1) {
		ctx->debug = verbose;
		ctx->debug_file = stderr;
        }

	if (opt_driver != NULL) {
		err = sc_set_card_driver(ctx, opt_driver);
		if (err) {
			fprintf(stderr, "Driver '%s' not found!\n", opt_driver);
			err = 1;
			goto end;
		}
	}

	err = util_connect_card(ctx, &card, opt_reader, opt_wait, 0);
	if (err)
		goto end;

	if (opt_startfile) {
		if(*opt_startfile) {
			char startpath[1024];
			char *args[] = { startpath };

			strncpy(startpath, opt_startfile, sizeof(startpath)-1);
			r = do_cd(1, args);
			if (r) {
				printf("unable to select file %s: %s\n",
					opt_startfile, sc_strerror(r));
				return -1;
			}
		}
	} else {
		sc_format_path("3F00", &current_path);
		r = sc_select_file(card, &current_path, &current_file);
		if (r) {
			printf("unable to select MF: %s\n", sc_strerror(r));
			return 1;
		}
	}

	r = sc_card_ctl(card, SC_CARDCTL_LIFECYCLE_SET, &lcycle);
	if (r && r != SC_ERROR_NOT_SUPPORTED)
		printf("unable to change lifecycle: %s\n", sc_strerror(r));

	switch (argc - optind) {
	default:
		util_print_usage_and_die(app_name, options, option_help, "[SCRIPT]");
		break;
	case 0:
		script = stdin;
		break;
	case 1:
		if (strcmp(argv[optind], "-") == 0) {
			script = stdin;
		}
		else if ((script = fopen(argv[optind], "r")) == NULL) {
			util_print_usage_and_die(app_name, options, option_help, "[SCRIPT]");
		}
		break;
	}

	while (!feof(script)) {
		struct command *cmd;
		char prompt[3*SC_MAX_PATH_STRING_SIZE];

		sprintf(prompt, "OpenSC [%s]> ", path_to_filename(&current_path, '/'));
		line = read_cmdline(script, prompt);
		if (line == NULL)
			break;
		cargc = parse_cmdline(line, cargv, DIM(cargv));
		if ((cargc < 1) || (*cargv[0] == '#'))
			continue;
		for (r=cargc; r < (int)DIM(cargv); r++)
			cargv[r] = "";
		cmd = ambiguous_match(cmds, cargv[0]);
		if (cmd == NULL) {
			do_help(0, NULL);
		} else {
			cmd->func(cargc-1, cargv+1);
		}
	}
end:
	die(err);

	return 0; /* not reached */
}
Beispiel #28
0
void __init setup_arch(char **cmdline_p)
{
	struct tag *tags = (struct tag *)&init_tags;
	struct machine_desc *mdesc;
	char *from = default_command_line;

	ROOT_DEV = MKDEV(0, 255);

	setup_processor();
	mdesc = setup_machine(machine_arch_type);
	machine_name = mdesc->name;

	if (mdesc->soft_reboot)
		reboot_setup("s");

	if (mdesc->param_offset)
		tags = phys_to_virt(mdesc->param_offset);

	/*
	 * Do the machine-specific fixups before we parse the
	 * parameters or tags.
	 */
	if (mdesc->fixup)
		mdesc->fixup(mdesc, (struct param_struct *)tags,
			     &from, &meminfo);

	/*
	 * If we have the old style parameters, convert them to
	 * a tag list.
	 */
	if (tags->hdr.tag != ATAG_CORE)
		convert_to_tag_list(tags);

	if (tags->hdr.tag == ATAG_CORE) {
		if (meminfo.nr_banks != 0)
			squash_mem_tags(tags);
		parse_tags(tags);
	}

	if (meminfo.nr_banks == 0) {
		meminfo.nr_banks      = 1;
		meminfo.bank[0].start = PHYS_OFFSET;
		meminfo.bank[0].size  = MEM_SIZE;
	}

	init_mm.start_code = (unsigned long) &_text;
	init_mm.end_code   = (unsigned long) &_etext;
	init_mm.end_data   = (unsigned long) &_edata;
	init_mm.brk	   = (unsigned long) &_end;

	memcpy(saved_command_line, from, COMMAND_LINE_SIZE);
	saved_command_line[COMMAND_LINE_SIZE-1] = '\0';
	parse_cmdline(&meminfo, cmdline_p, from);
	bootmem_init(&meminfo);
	paging_init(&meminfo, mdesc);
	request_standard_resources(&meminfo, mdesc);

	/*
	 * Set up various architecture-specific pointers
	 */
	init_arch_irq = mdesc->init_irq;

#ifdef CONFIG_VT
#if defined(CONFIG_VGA_CONSOLE)
	conswitchp = &vga_con;
#elif defined(CONFIG_DUMMY_CONSOLE)
	conswitchp = &dummy_con;
#endif
#endif
}
Beispiel #29
0
/* Command line parser */
static void
parse_cmdline(int argc, char **argv)
{
	int c;

	struct option long_options[] = {
		{"use-file",          required_argument, 0, 'f'},
		{"vrrp",              no_argument,       0, 'P'},
		{"check",             no_argument,       0, 'C'},
		{"log-console",       no_argument,       0, 'l'},
		{"log-detail",        no_argument,       0, 'D'},
		{"log-facility",      required_argument, 0, 'S'},
		{"release-vips",      no_argument,       0, 'X'},
		{"dont-release-vrrp", no_argument,       0, 'V'},
		{"dont-release-ipvs", no_argument,       0, 'I'},
		{"dont-respawn",      no_argument,       0, 'R'},
		{"dont-fork",         no_argument,       0, 'n'},
		{"dump-conf",         no_argument,       0, 'd'},
		{"pid",               required_argument, 0, 'p'},
		{"vrrp_pid",          required_argument, 0, 'r'},
		{"checkers_pid",      required_argument, 0, 'c'},
 #ifdef _WITH_SNMP_
		{"snmp",              no_argument,       0, 'x'},
 #endif
		{"version",           no_argument,       0, 'v'},
		{"help",              no_argument,       0, 'h'},
		{0, 0, 0, 0}
	};

#ifdef _WITH_SNMP_
	while ((c = getopt_long(argc, argv, "vhlndVIDRS:f:PCp:c:r:x", long_options, NULL)) != EOF) {
#else
	while ((c = getopt_long(argc, argv, "vhlndVIDRS:f:PCp:c:r:", long_options, NULL)) != EOF) {
#endif
		switch (c) {
		case 'v':
			fprintf(stderr, VERSION_STRING);
			exit(0);
			break;
		case 'h':
			usage(argv[0]);
			exit(0);
			break;
		case 'l':
			debug |= DBG_OPT_LOG_CONSOLE;
			break;
		case 'n':
			debug |= DBG_OPT_DONT_FORK;
			break;
		case 'd':
			debug |= DBG_OPT_DUMP_CONF;
			break;
		case 'V':
		 	debug |= DBG_OPT_DONT_RELEASE_VRRP;
			break;
		case 'I':
			debug |= DBG_OPT_DONT_RELEASE_IPVS;
			break;
		case 'D':
			debug |= DBG_OPT_LOG_DETAIL;
			break;
		case 'R':
			debug |= DBG_OPT_DONT_RESPAWN;
			break;
		case 'X':
		        debug |= DBG_OPT_RELEASE_VIPS;
			break;
		case 'S':
			log_facility = LOG_FACILITY[atoi(optarg)].facility;
			break;
		case 'f':
			conf_file = optarg;
			break;
		case 'P':
			daemon_mode |= 1;
			break;
		case 'C':
			daemon_mode |= 2;
			break;
		case 'p':
			main_pidfile = optarg;
			break;
		case 'c':
			checkers_pidfile = optarg;
			break;
		case 'r':
			vrrp_pidfile = optarg;
			break;
#ifdef _WITH_SNMP_
		case 'x':
			snmp = 1;
			break;
#endif
		default:
			exit(0);
			break;
		}
	}

	if (optind < argc) {
		printf("Unexpected argument(s): ");
		while (optind < argc)
			printf("%s ", argv[optind++]);
		printf("\n");
	}
}

/* Entry point */
int
main(int argc, char **argv)
{
	/* Init debugging level */
	mem_allocated = 0;
	debug = 0;

	/*
	 * Parse command line and set debug level.
	 * bits 0..7 reserved by main.c
	 */
	parse_cmdline(argc, argv);

	openlog(PROG, LOG_PID | ((debug & DBG_OPT_LOG_CONSOLE) ? LOG_CONS : 0),
		log_facility);
	log_message(LOG_INFO, "Starting " VERSION_STRING);

	/* Check if keepalived is already running */
	if (keepalived_running(daemon_mode)) {
		log_message(LOG_INFO, "daemon is already running");
		goto end;
	}

	if (debug & DBG_OPT_LOG_CONSOLE)
		enable_console_log();

	/* daemonize process */
	if (!(debug & DBG_OPT_DONT_FORK))
		xdaemon(0, 0, 0);

	/* write the father's pidfile */
	if (!pidfile_write(main_pidfile, getpid()))
		goto end;

#ifndef _DEBUG_
	/* Signal handling initialization  */
	signal_init();
#endif

	/* Create the master thread */
	master = thread_make_master();

	/* Init daemon */
	start_keepalived();

#ifndef _DEBUG_
	/* Launch the scheduling I/O multiplexer */
	launch_scheduler();

	/* Finish daemon process */
	stop_keepalived();
#endif

	/*
	 * Reached when terminate signal catched.
	 * finally return from system
	 */
end:
	closelog();
	exit(0);
}
Beispiel #30
0
int main(int argc, char **argv){
  CmdLine cmd_line = parse_cmdline(argc,argv,sizeof(Element));
  long long As=0;
  long long Cs=0;
  long long Gs=0;
  long long Ts=0;
  long long Us=0;

  int max_read_length = 1000;

  FILE* fp = fopen(cmd_line.input_filename, "r"); 
  if (fp == NULL){
    fprintf(stderr,"cannot open file:%s\n",cmd_line.input_filename);
    exit(1); //TODO - prefer to print warning and skip file and return an error code?
  }


  //----------------------------------
  // preallocate the memory used to read the sequences
  //----------------------------------
  Sequence * seq = malloc(sizeof(Sequence));
  if (seq == NULL){
    fputs("Out of memory trying to allocate Sequence\n",stderr);
    exit(1);
  }
  alloc_sequence(seq,max_read_length,LINE_MAX, cmd_line.quality_offset);
  
  int entry_length=0;
  boolean new_entry = true;
  boolean full_entry;
  do {

    switch (cmd_line.input_file_format) {
    case FASTQ:
      entry_length = read_sequence_from_fastq(fp,seq,max_read_length);
      break;
      
    case FASTA:
   
    entry_length = read_sequence_from_fasta(fp,seq,max_read_length,new_entry,&full_entry,0);
    new_entry = full_entry;
    break;
    }

    int i;
    for(i=0;i<entry_length;i++){
      //printf("index %i char %c\n",i,seq->seq[i]);

      switch (seq->seq[i])
	{
	  
	case 'A':
	  As++;
	  break;
	case 'C':
	  Cs++;
	  break;
	case 'G':
	  Gs++;
	  break;
	case 'T':
	  Ts++;
	  break;
	case 'a':
	  As++;
	  break;
	case 'c':
	  Cs++;
	  break;
	case 'g':
	  Gs++;
	  break;
	case 't':
	  Ts++;
	  break;
	default:
	  Us++;
	}
      
    }
    
  } while (entry_length>0);
  
  long long total = As + Cs + Gs + Ts + Us;

  printf("%qd As counted - %5.2f%%\n",As, (As*100.0)/total);
  printf("%qd Cs counted - %5.2f%%\n",Cs,(Cs*100.0)/total);
  printf("%qd Gs counted - %5.2f%%\n",Gs,(Gs*100.0)/total);
  printf("%qd Ts counted - %5.2f%%\n",Ts,(Ts*100.0)/total);
  printf("%qd Us counted - %5.2f%%\n",Us,(Us*100.0)/total);
  
  return 0;
}