コード例 #1
0
ファイル: buffer.c プロジェクト: sharan-wisc/756-project
/*
   Cartesian product of option sets with on-the-fly pruning.
   Update rules:

   T = min(T1, T2)
   L = L1 + L2

   Returns freshly created options list Z.
*/
static Options
options_combine(Options Z1, Options Z2)
{
  Options Z, o1, o2;
  Options *tail;
  Nat len=0;
  /* Combine every option element from Z1 with every option element from
     Z2. The merge operation is symmetric so this approach is sufficient
     to generate all possible combinations. The merge results are stored
     in a new list Z.
     Of course this list need not be ordered and very likely contains
     redundant options, therefore must explicitly sort/filter the list.
  */

  tail=&Z;
  for (o1 = Z1; o1; o1 = ONEXT(o1))
    for (o2 = Z2; o2; o2 = ONEXT(o2)) {
      /* Merge o1 and o2 */
        *tail = options_merge(o1, o2); 
        tail=&ONEXT(*tail);
        len++;
    }
  if (debug) options_show(stdout, Z, "test");

  /*   Z=*tail;*/
  Z = options_filter(Z, len); 

  /* Delete original lists: */
  options_free(Z1);
  options_free(Z2);
  return Z;
}
コード例 #2
0
int main(int argc, const char** argv)
{
  struct sockaddr_storage addr;
  socklen_t addrlen;
  options_t options;
  workers_t workers;
  uint8_t running, ready;
  sigset_t set;

  /* Check arguments. */
  if (argc == 1) {
    usage(argv[0]);
    return -1;
  }

  if (build_socket_address(argv[argc - 1], &addr, &addrlen) < 0) {
    fprintf(stderr, "Invalid socket address '%s'.\n", argv[argc - 1]);
    return -1;
  }

  if (options_parse(argc, argv, &options) < 0) {
    usage(argv[0]);
    return -1;
  }

  /* Block signals SIGINT and SIGTERM. */
  sigemptyset(&set);
  sigaddset(&set, SIGINT);
  sigaddset(&set, SIGTERM);
  if (pthread_sigmask(SIG_BLOCK, &set, NULL) < 0) {
    fprintf(stderr, "Error blocking signals.\n");

    options_free(&options);
    return -1;
  }

  /* Create worker threads. */
  if (workers_create((const struct sockaddr*) &addr,
                     addrlen,
                     &options,
                     &running,
                     &ready,
                     &workers) < 0) {
    fprintf(stderr, "Error creating worker threads.\n");

    options_free(&options);
    return -1;
  }

  /* Join worker threads. */
  workers_join(&workers, &running);

  /* Show statistics. */
  workers_statistics(&workers);

  options_free(&options);

  return 0;
}
コード例 #3
0
ファイル: helper-all.c プロジェクト: splone/splonebox-core
void connect_to_db(void)
{
  redisReply *reply;
  options *globaloptions;
  struct timeval timeout = { 1, 500000 };

  if (options_init_from_boxrc() < 0) {
      LOG_ERROR("Reading config failed--see warnings above. "
              "For usage, try -h.");
      return;
  }

  globaloptions = options_get();

  /* connect to database */
  assert_int_equal(0, db_connect(
      fmt_addr(&globaloptions->RedisDatabaseListenAddr),
      globaloptions->RedisDatabaseListenPort, timeout,
      globaloptions->RedisDatabaseAuth));

  reply = redisCommand(rc, "FLUSHALL");

  freeReplyObject(reply);

  options_free(globaloptions);
}
コード例 #4
0
CTEST(node_serial_test, leaf_empty)
{
	int ret = 0;
	int fd = ness_os_open(BRT_FILE, O_RDWR | O_CREAT, 0777);
	struct block *b = block_new();
	struct hdr *hdr = (struct hdr*)xcalloc(1, sizeof(*hdr));
	struct options *opts = options_new();

	/*
	 * dummy brt leaf
	 */
	uint64_t nid = 3;

	struct node *dummy_leaf = leaf_alloc_empty(nid);
	leaf_alloc_bsm(dummy_leaf);
	ret = serialize_node_to_disk(fd, b, dummy_leaf, hdr);
	ASSERT_TRUE(ret > 0);
	//free
	node_free(dummy_leaf);

	struct node *dummy_leaf1;
	ret = deserialize_node_from_disk(fd, b, nid, &dummy_leaf1, 0);
	ASSERT_TRUE(ret > 0);
	ASSERT_EQUAL(0, basement_count(dummy_leaf1->u.l.le->bsm));
	//free
	node_free(dummy_leaf1);

	ness_os_close(fd);
	block_free(b);
	xfree(hdr);
	options_free(opts);
	xcheck_all_free();
}
コード例 #5
0
ファイル: app.c プロジェクト: HoNooD/dnscrypt-proxy
static void
proxy_context_free(ProxyContext * const proxy_context)
{
    if (proxy_context == NULL) {
        return;
    }
    options_free(proxy_context);
    logger_close(proxy_context);
}
コード例 #6
0
int
main(int argc, char *argv[])
{
    FILE *out = stdout;
    struct options *options = options_alloc(argc, argv);
    
    if (options->error || options->help) {
        options_print_usage(options);
        return options->error? EXIT_FAILURE : EXIT_SUCCESS;
    }
    
    if (action_game == options->action) {
        play_game(options->rnd);
    } else if (action_tui == options->action) {
        run_tui();
    } else {
        fprintf(out, "Fiends and Fortune\n");
        switch (options->action) {
            case action_character:
                generate_character(options->rnd, out, options->character_method);
                break;
            case action_check:
                check(out, options->check_constant);
                break;
            case action_dungeon:
                if (options->dungeon_type_small) {
                    generate_sample_dungeon(options->rnd, out);
                } else {
                    generate_random_dungeon(options->rnd, out);
                }
                break;
            case action_each:
                generate_each_treasure(options->rnd, out);
                break;
            case action_magic:
                generate_magic_items(options->rnd, out, options->magic_count);
                break;
            case action_map:
                generate_map(options->rnd, out);
                break;
            case action_table:
                generate_treasure_type_table(out);
                break;
            case action_treasure:
                generate_treasure_type(options->rnd, out, options->treasure_type);
                break;
            default:
                fprintf(stderr, "%s: unrecognized option\n", options->command_name);
                break;
        }
        fprintf(out, "\n");
    }
    
    options_free(options);
    alloc_count_is_zero_or_die();
    return EXIT_SUCCESS;
}
コード例 #7
0
ファイル: init.c プロジェクト: richardelling/fio
void free_shm(void)
{
	if (threads) {
		file_hash_exit();
		flow_exit();
		fio_debug_jobp = NULL;
		free_threads_shm();
	}

	options_free(fio_options, &def_thread);
	scleanup();
}
コード例 #8
0
ファイル: main.c プロジェクト: kkalmaz/psmame
int CLIB_DECL main(int argc, char *argv[])
{
	int result = -1;
	clock_t begin_time;
	double elapsed_time;
	core_options *messtest_options = NULL;

	test_count = 0;
	failure_count = 0;
	messtest_options = NULL;

	/* register options */
	messtest_options = options_create(messtest_fail);
	options_add_entries(messtest_options, messtest_option_entries);
	options_set_option_callback(messtest_options, OPTION_GAMENAME, handle_arg);

	/* run MAME's validity checks; if these fail cop out now */
	/* NPW 16-Sep-2006 - commenting this out because this cannot be run outside of MAME */
	//if (mame_validitychecks(-1))
	//  goto done;
	/* run Imgtool's validity checks; if these fail cop out now */
	if (imgtool_validitychecks())
		goto done;

	begin_time = clock();

	/* parse the commandline */
	if (options_parse_command_line(messtest_options, argc, argv, OPTION_PRIORITY_CMDLINE,TRUE))
	{
		fprintf(stderr, "Error while parsing cmdline\n");
		goto done;
	}

	if (test_count > 0)
	{
		elapsed_time = ((double) (clock() - begin_time)) / CLOCKS_PER_SEC;

		fprintf(stderr, "Tests complete; %i test(s), %i failure(s), elapsed time %.2f\n",
			test_count, failure_count, elapsed_time);
	}
	else
	{
		fprintf(stderr, "Usage: %s [test1] [test2]...\n", argv[0]);
	}
	result = failure_count;

done:
	if (messtest_options)
		options_free(messtest_options);
	return result;
}
コード例 #9
0
ファイル: tcursor-test.c プロジェクト: Fleurer/nessDB
CTEST(cursor, empty)
{
	int ret;
	struct options *opts;
	struct status *status;
	struct cache *cache;
	struct tree *tree;

	/* create */
	opts = options_new();
	status = status_new();
	cache = dbcache_new(opts);
	tree = tree_new(DBPATH0, opts, status, cache, 1);


	/* cursor */
	struct cursor *cur;

	cur = cursor_new(tree);

	/* first */
	tree_cursor_first(cur);
	ret = tree_cursor_valid(cur);
	ASSERT_EQUAL(0, ret);

	/* last */
	tree_cursor_last(cur);
	ret = tree_cursor_valid(cur);
	ASSERT_EQUAL(0, ret);

	/* next */
	tree_cursor_next(cur);
	ret = tree_cursor_valid(cur);
	ASSERT_EQUAL(0, ret);

	cursor_free(cur);

	/* free */
	dbcache_free(cache);
	tree_free(tree);
	options_free(opts);
	status_free(status);
	xcheck_all_free();
}
コード例 #10
0
ファイル: log-test.c プロジェクト: Fleurer/nessDB
CTEST(log, read) {
	uint64_t lsn = 112;
	struct options *opts = options_new();
	struct logr *lgr = logr_open(opts, lsn);

	struct msg k;
	struct msg v;
	msgtype_t type;
	uint32_t tid;

	int i = 0;
	while (logr_read(lgr, &k, &v, &type, &tid) == NESS_OK) {
		i++;
	}

	ASSERT_EQUAL(R, i);

	logr_close(lgr);
	options_free(opts);
}
コード例 #11
0
ファイル: log-test.c プロジェクト: Fleurer/nessDB
CTEST(log, write) {
	int i;
	char kbuf[KEY_SIZE];
	char vbuf[VAL_SIZE];

	uint32_t tbn = 0U;
	uint64_t lsn = 112;
	struct options *opts = options_new();
	struct logw *lgw = logw_open(opts, lsn);

	for (i = 0; i < R; i++) {
		memset(kbuf, 0 , KEY_SIZE);
		memset(vbuf, 0 , VAL_SIZE);
		snprintf(kbuf, KEY_SIZE, "key-%d", i);
		snprintf(vbuf, VAL_SIZE, "val-%d", i);

		struct msg k = {.data = kbuf, .size = KEY_SIZE};
		struct msg v = {.data = vbuf, .size = VAL_SIZE};

		logw_append(lgw, &k, &v, MSG_PUT, tbn);
	}

	uint32_t all_size;
	uint32_t one_size = 4	/* first length */
		+ 4		/* tid */
		+ 2		/* type */
		+ 4		/* key length */
		+ KEY_SIZE	/* key */
		+ 4		/*val length */
		+ VAL_SIZE	/* val */
		+ 4;		/* crc */

	all_size = R * one_size;
	ASSERT_EQUAL(all_size, lgw->size);

	logw_close(lgw);
	options_free(opts);
}
コード例 #12
0
ファイル: libmame_rungame.c プロジェクト: bji/libmame
LibMame_RunGameStatus LibMame_RunGame(int gamenum, bool benchmarking,
                                      const LibMame_RunGameOptions *options,
                                      const LibMame_RunGameCallbacks *cbs,
                                      void *callback_data)
{
    if (gamenum >= LibMame_Get_Game_Count()) {
        return LibMame_RunGameStatus_InvalidGameNum;
    }

    /* Set up MAME's "output channels" so that we accumulate it all in a
       buffer rather than dumping it to stdout/stderr/wherever */
    mame_set_output_channel(OUTPUT_CHANNEL_ERROR, output_callback, 0, 0, 0);
    mame_set_output_channel(OUTPUT_CHANNEL_WARNING, output_callback, 0, 0, 0);
    mame_set_output_channel(OUTPUT_CHANNEL_INFO, output_callback, 0, 0, 0);
    mame_set_output_channel(OUTPUT_CHANNEL_DEBUG, output_callback, 0, 0, 0);
    mame_set_output_channel(OUTPUT_CHANNEL_VERBOSE, output_callback, 0, 0, 0);
    mame_set_output_channel(OUTPUT_CHANNEL_LOG, output_callback, 0, 0, 0);

    /* Set the unfortunate globals.  Would greatly prefer to allocate a
       new one of these and pass it to MAME, having it pass it back in the
       osd_ callbacks. */
    g_state.callbacks = cbs;
    g_state.callback_data = callback_data;

    /* Save the game number */
    g_state.gamenum = gamenum;

    /* Look up the game number of players and controllers */
    g_state.maximum_player_count =
        LibMame_Get_Game_MaxSimultaneousPlayers(gamenum);
    g_state.controllers = LibMame_Get_Game_AllControllers(gamenum);

    /* Set up options stuff for MAME.  If none were supplied, use the
       defaults. */
    core_options *mame_options;
    if (options == NULL) {
        LibMame_RunGameOptions default_options;
        LibMame_Set_Default_RunGameOptions(&default_options);
        mame_options = get_mame_options
            (&default_options, LibMame_Get_Game_Short_Name(gamenum));
    }
    else {
        mame_options = get_mame_options
            (options, LibMame_Get_Game_Short_Name(gamenum));
    }

    /* Haven't configured special inputs yet */
    g_state.special_inputs_configured = false;

    /* Not waiting for a pause */
    g_state.waiting_for_pause = false;

    /* Run the game */
    int result;
    {
        libmame_rungame_osd_interface osd;
        result = mame_execute(osd, mame_options, benchmarking);
    }

    /* Free the options */
    options_free(mame_options);

    /* Convert the resulting MAME code to a libmame code and return */
    switch (result) {
    case MAMERR_NONE:
        return LibMame_RunGameStatus_Success;
    case MAMERR_FAILED_VALIDITY:
        return LibMame_RunGameStatus_FailedValidityCheck;
    case MAMERR_MISSING_FILES:
        return LibMame_RunGameStatus_MissingFiles;
    case MAMERR_FATALERROR:
    case MAMERR_DEVICE:
    case MAMERR_IDENT_NONROMS:
    case MAMERR_IDENT_PARTIAL:
    case MAMERR_IDENT_NONE:
        return LibMame_RunGameStatus_GeneralError;
    case MAMERR_NO_SUCH_GAME:
        return LibMame_RunGameStatus_NoSuchGame;
    case MAMERR_INVALID_CONFIG:
        return LibMame_RunGameStatus_InvalidConfig;
    }

    return LibMame_RunGameStatus_GeneralError;
}
コード例 #13
0
CTEST(node_serial_test, node_2th_part_empty)
{
	int ret = 0;
	NID nid;
	uint32_t n_children = 3;
	int fd = ness_os_open(BRT_FILE, O_RDWR | O_CREAT, 0777);
	struct block *b = block_new();
	struct hdr *hdr = (struct hdr*)xcalloc(1, sizeof(*hdr));
	struct options *opts = options_new();

	/*
	 * serialize
	 */
	struct node *dummy_node;

	hdr->last_nid++;
	nid = hdr->last_nid;
	dummy_node = nonleaf_alloc_empty(nid, 1, n_children);
	nonleaf_alloc_buffer(dummy_node);

	struct msg p0;
	p0.size = 6;
	p0.data = "pivot0";
	msgcpy(&dummy_node->u.n.pivots[0], &p0);

	struct msg p1;
	p1.size = 6;
	p1.data = "pivot1";
	msgcpy(&dummy_node->u.n.pivots[1], &p1);

	MSN msn = 0U;
	struct xids *xids = NULL;
	struct msg k, v;
	k.size = 5;
	k.data = "hello";
	v.size = 5;
	v.data = "world";
	basement_put(dummy_node->u.n.parts[0].buffer, &k, &v, MSG_INSERT, msn,
	             xids);


	hdr->method = NESS_QUICKLZ_METHOD;
	ret = serialize_node_to_disk(fd, b, dummy_node, hdr);
	ASSERT_TRUE(ret > 0);
	node_free(dummy_node);

	//deserialize
	int light = 0;
	struct node *dummy_node1;
	ret = deserialize_node_from_disk(fd, b, nid, &dummy_node1, light);
	ASSERT_TRUE(ret > 0);

	ASSERT_EQUAL(1, dummy_node1->height);
	ASSERT_EQUAL(3, dummy_node1->u.n.n_children);
	ASSERT_DATA((const unsigned char*)"pivot0",
	            6,
	            (const unsigned char*)dummy_node1->u.n.pivots[0].data,
	            dummy_node1->u.n.pivots[0].size);

	ASSERT_DATA((const unsigned char*)"pivot1",
	            6,
	            (const unsigned char*)dummy_node1->u.n.pivots[1].data,
	            dummy_node1->u.n.pivots[1].size);
	ASSERT_EQUAL(3, dummy_node1->u.n.n_children);

	if (!light) {
		int cmp;
		struct basement_iter iter;
		struct basement *bsm;

		bsm = dummy_node1->u.n.parts[0].buffer;
		basement_iter_init(&iter, bsm);

		int mb_c = basement_count(dummy_node1->u.n.parts[0].buffer);
		ASSERT_EQUAL(1, mb_c);
		basement_iter_seek(&iter, &k);
		ret = basement_iter_valid(&iter);
		ASSERT_EQUAL(1, ret);
		cmp = msg_key_compare(&k, &iter.key);
		ASSERT_EQUAL(0, cmp);
		cmp = msg_key_compare(&v, &iter.val);
		ASSERT_EQUAL(0, cmp);

		mb_c = basement_count(dummy_node1->u.n.parts[1].buffer);
		ASSERT_EQUAL(0, mb_c);
	}
	node_free(dummy_node1);

	ness_os_close(fd);
	block_free(b);
	xfree(hdr);
	options_free(opts);
	xcheck_all_free();
}
コード例 #14
0
ファイル: tmux.c プロジェクト: ThomasAdam/tmux-ARCHIVED
int
main(int argc, char **argv)
{
	struct client_ctx	 cctx;
	struct msg_command_data	 cmddata;
	struct buffer		*b;
	struct cmd_list		*cmdlist;
 	struct cmd		*cmd;
	struct pollfd	 	 pfd;
	struct hdr	 	 hdr;
	const char		*shell;
	struct passwd		*pw;
	char			*path, *label, *cause, *home, *pass = NULL;
	char			 cwd[MAXPATHLEN];
	int	 		 retcode, opt, flags, unlock, start_server;

	unlock = flags = 0;
	label = path = NULL;
        while ((opt = getopt(argc, argv, "28df:L:qS:uUVv")) != -1) {
                switch (opt) {
		case '2':
			flags |= IDENTIFY_256COLOURS;
			flags &= ~IDENTIFY_88COLOURS;
			break;
		case '8':
			flags |= IDENTIFY_88COLOURS;
			flags &= ~IDENTIFY_256COLOURS;
			break;
		case 'f':
			cfg_file = xstrdup(optarg);
			break;
		case 'L':
			if (path != NULL) {
				log_warnx("-L and -S cannot be used together");
				exit(1);
			}
			if (label != NULL)
				xfree(label);
			label = xstrdup(optarg);
			break;
		case 'S':
			if (label != NULL) {
				log_warnx("-L and -S cannot be used together");
				exit(1);
			}
			if (path != NULL)
				xfree(path);
			path = xstrdup(optarg);
			break;
		case 'q':
			be_quiet = 1;
			break;
		case 'u':
			flags |= IDENTIFY_UTF8;
			break;
		case 'U':
			unlock = 1;
			break;
		case 'd':
			flags |= IDENTIFY_HASDEFAULTS;
			break;
		case 'v':
			debug_level++;
			break;
		case 'V':
			printf("%s " BUILD "\n", __progname);
			exit(0);
                default:
			usage();
                }
        }
	argc -= optind;
	argv += optind;

	log_open_tty(debug_level);
	siginit();

	options_init(&global_options, NULL);
	options_set_number(&global_options, "bell-action", BELL_ANY);
	options_set_number(&global_options, "buffer-limit", 9);
	options_set_number(&global_options, "display-time", 750);
	options_set_number(&global_options, "history-limit", 2000);
	options_set_number(&global_options, "message-bg", 3);
	options_set_number(&global_options, "message-fg", 0);
	options_set_number(&global_options, "message-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_options, "prefix", META);
	options_set_number(&global_options, "repeat-time", 500);
	options_set_number(&global_options, "set-titles", 1);
	options_set_number(&global_options, "lock-after-time", 0);
	options_set_number(&global_options, "set-remain-on-exit", 0);
	options_set_number(&global_options, "status", 1);
	options_set_number(&global_options, "status-bg", 2);
	options_set_number(&global_options, "status-fg", 0);
	options_set_number(&global_options, "status-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_options, "status-interval", 15);
	options_set_number(&global_options, "status-left-length", 10);
	options_set_number(&global_options, "status-right-length", 40);
	options_set_string(&global_options, "status-left", "[#S]");
	options_set_string(
	    &global_options, "status-right", "\"#24T\" %%H:%%M %%d-%%b-%%y");
	options_set_number(&global_options, "status-keys", MODEKEY_EMACS);
	options_init(&global_window_options, NULL);
	options_set_number(&global_window_options, "aggressive-resize", 0);
	options_set_number(&global_window_options, "clock-mode-colour", 4);
	options_set_number(&global_window_options, "clock-mode-style", 1);
	options_set_number(&global_window_options, "force-height", 0);
	options_set_number(&global_window_options, "force-width", 0);
	options_set_number(&global_window_options, "automatic-rename", 1);
	options_set_number(&global_window_options, "mode-bg", 3);
	options_set_number(&global_window_options, "mode-fg", 0);
	options_set_number(
	    &global_window_options, "mode-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_window_options, "mode-keys", MODEKEY_EMACS);
	options_set_number(&global_window_options, "monitor-activity", 0);
	options_set_number(&global_window_options, "utf8", 0);
	options_set_number(&global_window_options, "xterm-keys", 0);
 	options_set_number(&global_window_options, "remain-on-exit", 0);
	options_set_number(&global_window_options, "window-status-bg", 8);
	options_set_number(&global_window_options, "window-status-fg", 8);
	options_set_number(&global_window_options, "window-status-attr", 0);

	if (cfg_file == NULL) {
		home = getenv("HOME");
		if (home == NULL || *home == '\0') {
			pw = getpwuid(getuid());
			if (pw != NULL)
				home = pw->pw_dir;
			endpwent();
		}
		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
		if (access(cfg_file, R_OK) != 0) {
			xfree(cfg_file);
			cfg_file = NULL;
		}
	} else {
		if (access(cfg_file, R_OK) != 0) {
			log_warn("%s", cfg_file);
			exit(1);
		}
	}

	if (label == NULL)
		label = xstrdup("default");
	if (path == NULL && (path = makesockpath(label)) == NULL) {
		log_warn("can't create socket");
		exit(1);
	}
	xfree(label);

	shell = getenv("SHELL");
	if (shell == NULL || *shell == '\0') {
		pw = getpwuid(getuid());
		if (pw != NULL)
			shell = pw->pw_shell;
		endpwent();
		if (shell == NULL || *shell == '\0')
			shell = _PATH_BSHELL;
	}
	options_set_string(
	    &global_options, "default-command", "exec %s", shell);
	

	if (getcwd(cwd, sizeof cwd) == NULL) {
		log_warn("getcwd");
		exit(1);
	}
	options_set_string(&global_options, "default-path", "%s", cwd);

	if (unlock) {
		if (argc != 0) {
			log_warnx("can't specify a command when unlocking");
			exit(1);
		}
		cmdlist = NULL;
		if ((pass = getpass("Password: "******"%s", cause);
				exit(1);
			}
		}
		start_server = 0;
		TAILQ_FOREACH(cmd, cmdlist, qentry) {
			if (cmd->entry->flags & CMD_STARTSERVER) {
				start_server = 1;
				break;
			}
		}
	}
	
 	memset(&cctx, 0, sizeof cctx);
	if (client_init(path, &cctx, start_server, flags) != 0)
		exit(1);
	xfree(path);

	b = buffer_create(BUFSIZ);
	if (unlock) {
		cmd_send_string(b, pass);
		client_write_server(
		    &cctx, MSG_UNLOCK, BUFFER_OUT(b), BUFFER_USED(b));
	} else {
		cmd_list_send(cmdlist, b);
		cmd_list_free(cmdlist);
		client_fill_session(&cmddata);
		client_write_server2(&cctx, MSG_COMMAND,
		    &cmddata, sizeof cmddata, BUFFER_OUT(b), BUFFER_USED(b));
	}
	buffer_destroy(b);

	retcode = 0;
	for (;;) {
		pfd.fd = cctx.srv_fd;
		pfd.events = POLLIN;
		if (BUFFER_USED(cctx.srv_out) > 0)
			pfd.events |= POLLOUT;

		if (poll(&pfd, 1, INFTIM) == -1) {
			if (errno == EAGAIN || errno == EINTR)
				continue;
			fatal("poll failed");
		}

		if (buffer_poll(&pfd, cctx.srv_in, cctx.srv_out) != 0)
			goto out;

	restart:
		if (BUFFER_USED(cctx.srv_in) < sizeof hdr)
			continue;
		memcpy(&hdr, BUFFER_OUT(cctx.srv_in), sizeof hdr);
		if (BUFFER_USED(cctx.srv_in) < (sizeof hdr) + hdr.size)
			continue;
		buffer_remove(cctx.srv_in, sizeof hdr);

		switch (hdr.type) {
		case MSG_EXIT:
		case MSG_SHUTDOWN:
			goto out;
		case MSG_ERROR:
			retcode = 1;
			/* FALLTHROUGH */
		case MSG_PRINT:
			if (hdr.size > INT_MAX - 1)
				fatalx("bad MSG_PRINT size");
			log_info("%.*s",
			    (int) hdr.size, BUFFER_OUT(cctx.srv_in));
			if (hdr.size != 0)
				buffer_remove(cctx.srv_in, hdr.size);
			goto restart;
		case MSG_READY:
			retcode = client_main(&cctx);
			goto out;
		default:
			fatalx("unexpected command");
		}
	}

out:
	options_free(&global_options);
	options_free(&global_window_options);

	close(cctx.srv_fd);
	buffer_destroy(cctx.srv_in);
	buffer_destroy(cctx.srv_out);

#ifdef DEBUG
	xmalloc_report(getpid(), "client");
#endif
	return (retcode);
}
コード例 #15
0
ファイル: main.c プロジェクト: darcyg/u2pnpd
int main(int argc, char *argv[])
{
	UpnpDevice_Handle upnp_handle;
	UpnpDevice_Handle upnp_device;
	char *device_desc = NULL;
	int rv = EXIT_FAILURE;
	struct sigaction sa;

	shutdown_flag = 0;

	/* init options, preset some defaults and parse command line arguments */
	options = options_init();
	options_parse_cli(argc, argv, options);

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = signal_handler;
	sa.sa_flags = 0;
	sigfillset(&sa.sa_mask);

	if (sigaction(SIGINT, &sa, NULL) < 0) {
		perror("sigaction");
		return EXIT_FAILURE;
	}
	if (sigaction(SIGTERM, &sa, NULL) < 0) {
		perror("sigaction");
		return EXIT_FAILURE;
	}

#ifdef UPNP_ENABLE_IPV6
	rv = UpnpInit2(options->interface, 0);
#else
	if (options->interface)
		fprintf(stderr, "Warning: ignoring interface argument, not supported by libupnp.\n");
	rv = UpnpInit(NULL, 0);
#endif
	if (rv != UPNP_E_SUCCESS) {
		fprintf(stderr, "UpnpInit failed: %d\n", rv);
		return EXIT_FAILURE;
	}

	rv = UpnpEnableWebserver(1);
	if (rv != UPNP_E_SUCCESS) {
		fprintf(stderr, "Could not enabled UPnP's internal HTTP server.\n");
		goto upnp_finish;
	}

	device_desc = generate_device_desc(options);
	if (!device_desc) {
		fprintf(stderr, "Could not generated the UPnP device description.\n");
		goto upnp_finish;
	}

	rv = UpnpRegisterRootDevice2(UPNPREG_BUF_DESC, device_desc, strlen(device_desc), 1,
	                             upnp_callback, &upnp_device, &upnp_device);
	if (rv != UPNP_E_SUCCESS) {
		fprintf(stderr, "Failed to register UPnP root device.\n");
		goto free_out;
	}

	rv = UpnpSendAdvertisement(upnp_device, UPNP_ALIVE_INTERVAL);
	if (rv != UPNP_E_SUCCESS) {
		fprintf(stderr, "Failed to announce UPnP device.\n");
		goto upnp_unregister;
	}

	while (!shutdown_flag)
		pause();

	rv = EXIT_SUCCESS;

upnp_unregister:
	UpnpUnRegisterRootDevice(upnp_device);
free_out:
	if (device_desc)
		free(device_desc);
upnp_finish:
	UpnpFinish();
err_out:
	options_free(options);
	return rv;
}
コード例 #16
0
ファイル: shd-main.c プロジェクト: desphunter/shadow
gint main_runShadow(gint argc, gchar* argv[]) {
    /* check the compiled GLib version */
    if (!GLIB_CHECK_VERSION(2, 32, 0)) {
        g_printerr("** GLib version 2.32.0 or above is required but Shadow was compiled against version %u.%u.%u\n",
            (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION);
        return EXIT_FAILURE;
    }

    if(GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION == 40) {
        g_printerr("** You compiled against GLib version %u.%u.%u, which has bugs known to break Shadow. Please update to a newer version of GLib.\n",
                    (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION);
        return EXIT_FAILURE;
    }

    /* check the that run-time GLib matches the compiled version */
    const gchar* mismatch = glib_check_version(GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
    if(mismatch) {
        g_printerr("** The version of the run-time GLib library (%u.%u.%u) is not compatible with the version against which Shadow was compiled (%u.%u.%u). GLib message: '%s'\n",
        glib_major_version, glib_minor_version, glib_micro_version,
        (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION,
        mismatch);
        return EXIT_FAILURE;
    }

    /* parse the options from the command line */
    gchar* cmds = g_strjoinv(" ", argv);
    gchar** cmdv = g_strsplit(cmds, " ", 0);
    g_free(cmds);
    Options* options = options_new(argc, cmdv);
    g_strfreev(cmdv);
    if(!options) {
        return EXIT_FAILURE;
    }

    /* if they just want the shadow version, print it and exit */
    if(options_doRunPrintVersion(options)) {
        g_printerr("%s running GLib v%u.%u.%u and IGraph v%s\n%s\n",
                SHADOW_VERSION_STRING,
                (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION,
#if defined(IGRAPH_VERSION)
                IGRAPH_VERSION,
#else
                "(n/a)",
#endif
                SHADOW_INFO_STRING);
        options_free(options);
        return EXIT_SUCCESS;
    }

    /* start up the logging subsystem to handle all future messages */
    Logger* shadowLogger = logger_new(options_getLogLevel(options));
    logger_setDefault(shadowLogger);

    /* disable buffering during startup so that we see every message immediately in the terminal */
    logger_setEnableBuffering(shadowLogger, FALSE);

    gint returnCode = _main_helper(options);

    options_free(options);
    Logger* logger = logger_getDefault();
    if(logger) {
        logger_setDefault(NULL);
        logger_unref(logger);
    }

    g_printerr("** Stopping Shadow, returning code %i (%s)\n", returnCode, (returnCode == 0) ? "success" : "error");
    return returnCode;
}
コード例 #17
0
ファイル: main.c プロジェクト: collinanderson/cptutils
int main(int argc, char** argv)
{
  struct gengetopt_args_info info;
  char   *infile = NULL, *outfile = NULL;
  glopt_t opt = {0};

  /* use gengetopt */

  if (options(argc, argv, &info) != 0)
    {
      fprintf(stderr, "failed to parse command line\n");
      return EXIT_FAILURE;
    }

  /* check arguments & transfer to opt structure */ 

  opt.verbose = info.verbose_given;

  opt.numsamp = info.samples_arg;

  if (opt.numsamp < 1)
    {
      fprintf(stderr,"bad number of samples %zu\n",opt.numsamp);
      return EXIT_FAILURE;
    }

  /* null outfile for stdout */

  outfile = (info.output_given ? info.output_arg : NULL);

  if (!outfile && opt.verbose)
    {
      fprintf(stderr,"verbosity suppressed (<stdout> for results)\n");
      opt.verbose = 0;
    }

  /* null infile for stdin */

  switch (info.inputs_num)
    {
    case 0:
      infile = NULL;
      break;
    case 1:
      infile = info.inputs[0];
      break;
    default:
      fprintf(stderr,"Sorry, only one file at a time\n");
      return EXIT_FAILURE;
    }
  
  if (opt.verbose)
    printf("This is gimplut (version %s)\n", VERSION);

  btrace_enable("gimplut");

  int err = gimplut(infile, outfile, opt);

  if (err)
    {
      btrace("failed (error %i)", err);
      btrace_print_stream(stderr, BTRACE_PLAIN);

      if (info.backtrace_file_given)
	{
	  int format = BTRACE_XML;
	  if (info.backtrace_format_given)
	    {
	      format = btrace_format(info.backtrace_format_arg);
	      if (format == BTRACE_ERROR)
		{
		  fprintf(stderr, "no such backtrace format %s\n", 
			  info.backtrace_format_arg);
		  return EXIT_FAILURE;
		}
	    }	  
	  btrace_print(info.backtrace_file_arg, format);
	}
    }
  else if (opt.verbose)
    printf("lookup table written to %s\n",(outfile ? outfile : "<stdin>"));

  btrace_reset();
  btrace_disable();

  if (opt.verbose)
    printf("done.\n");

  options_free(&info);

  return (err ? EXIT_FAILURE : EXIT_SUCCESS);
}
コード例 #18
0
ファイル: clifront.c プロジェクト: DarrenBranford/MAME4iOS
int cli_execute(int argc, char **argv, const options_entry *osd_options)
{
	core_options *options = NULL;
	const char *gamename_option;
	const game_driver *driver;
	int result = MAMERR_FATALERROR;
	astring gamename;
	astring exename;

	try
	{
		/* initialize the options manager and add the CLI-specific options */
		options = mame_options_init(osd_options);
		options_add_entries(options, cli_options);

		/* parse the command line first; if we fail here, we're screwed */
		if (options_parse_command_line(options, argc, argv, OPTION_PRIORITY_CMDLINE))
		{
			result = MAMERR_INVALID_CONFIG;
			goto error;
		}

		/* parse the simple commmands before we go any further */
		core_filename_extract_base(&exename, argv[0], TRUE);
		result = execute_simple_commands(options, exename);
		if (result != -1)
			goto error;

		/* find out what game we might be referring to */
		gamename_option = options_get_string(options, OPTION_GAMENAME);
		core_filename_extract_base(&gamename, gamename_option, TRUE);
		driver = driver_get_name(gamename);

		/* execute any commands specified */
		result = execute_commands(options, exename, driver);
		if (result != -1)
			goto error;

		/* if we don't have a valid driver selected, offer some suggestions */
		if (strlen(gamename_option) > 0 && driver == NULL)
		{
			const game_driver *matches[10];
			int drvnum;

			/* get the top 10 approximate matches */
			driver_list_get_approx_matches(drivers, gamename_option, ARRAY_LENGTH(matches), matches);

			/* print them out */
			fprintf(stderr, "\n\"%s\" approximately matches the following\n"
					"supported " GAMESNOUN " (best match first):\n\n", gamename_option);
			for (drvnum = 0; drvnum < ARRAY_LENGTH(matches); drvnum++)
				if (matches[drvnum] != NULL)
					fprintf(stderr, "%-18s%s\n", matches[drvnum]->name, matches[drvnum]->description);

			/* exit with an error */
			result = MAMERR_NO_SUCH_GAME;
			goto error;
		}

		/* run the game */
		result = mame_execute(options);
	}
	catch (emu_fatalerror &fatal)
	{
		fprintf(stderr, "%s\n", fatal.string());
		if (fatal.exitcode() != 0)
			result = fatal.exitcode();
	}
	catch (emu_exception &)
	{
		fprintf(stderr, "Caught unhandled emulator exception\n");
	}
	catch (std::bad_alloc &)
	{
		fprintf(stderr, "Out of memory!\n");
	}
	catch (...)
	{
		fprintf(stderr, "Caught unhandled exception\n");
	}

error:
	/* free our options and exit */
	if (options != NULL)
		options_free(options);

	/* report any unfreed memory */
	dump_unfreed_mem();
	return result;
}
コード例 #19
0
ファイル: main.c プロジェクト: mir-ror/moc
/* Run client and the server if needed. */
static void start_moc (const struct parameters *params, lists_t_strs *args)
{
	int server_sock;

	if (params->foreground) {
		set_me_server ();
		server_init (params->debug, params->foreground);
		server_loop ();
		return;
	}

	server_sock = server_connect ();

	if (server_sock != -1 && params->only_server)
		fatal ("Server is already running!");

	if (server_sock == -1) {
		int i = 0;
		int notify_pipe[2];
		ssize_t rc;

		printf ("Running the server...\n");

		/* To notify the client that the server socket is ready */
		if (pipe(notify_pipe))
			fatal ("pipe() failed: %s", xstrerror (errno));

		switch (fork()) {
		case 0: /* child - start server */
			set_me_server ();
			server_init (params->debug, params->foreground);
			rc = write (notify_pipe[1], &i, sizeof(i));
			if (rc < 0)
				fatal ("write() to notify pipe failed: %s", xstrerror (errno));
			close (notify_pipe[0]);
			close (notify_pipe[1]);
			server_loop ();
			options_free ();
			decoder_cleanup ();
			io_cleanup ();
			files_cleanup ();
			rcc_cleanup ();
			common_cleanup ();
			exit (EXIT_SUCCESS);
		case -1:
			fatal ("fork() failed: %s", xstrerror (errno));
		default:
			close (notify_pipe[1]);
			if (read(notify_pipe[0], &i, sizeof(i)) != sizeof(i))
				fatal ("Server exited!");
			close (notify_pipe[0]);
			server_sock = server_connect ();
			if (server_sock == -1) {
				perror ("server_connect()");
				fatal ("Can't connect to the server!");
			}
		}
	}

	if (params->only_server)
		send_int (server_sock, CMD_DISCONNECT);
	else {
		xsignal (SIGPIPE, SIG_IGN);
		if (!ping_server (server_sock))
			fatal ("Can't connect to the server!");

		init_interface (server_sock, params->debug, args);
		interface_loop ();
		interface_end ();
	}

	close (server_sock);
}
コード例 #20
0
static messtest_result_t run_test(int flags, messtest_results *results)
{
	const game_driver *driver;
	messtest_result_t rc;
	clock_t begin_time;
	double real_run_time;
	astring *fullpath = NULL;
	const char *device_opt;
	const char *fake_argv[2];
	core_options *opts;

	/* lookup driver */
	driver = driver_get_name(current_testcase.driver);

	/* cannot find driver? */
	if (driver == NULL)
	{
		report_message(MSG_FAILURE, "Cannot find driver '%s'", current_testcase.driver);
		return MESSTEST_RESULT_STARTFAILURE;
	}

	/* prepare testing state */
	current_command = current_testcase.commands;
	state = STATE_READY;
	test_flags = flags;
	screenshot_num = 0;
	runtime_hash = 0;
	had_failure = FALSE;
	//videoram = NULL;
	//videoram_size = 0;

	/* set up options */
	opts = mame_options_init(win_mess_opts);
	options_set_string(opts, OPTION_GAMENAME, driver->name, OPTION_PRIORITY_CMDLINE);
	if( current_testcase.bios )
		options_set_string(opts, OPTION_BIOS, current_testcase.bios, OPTION_PRIORITY_CMDLINE);
	options_set_bool(opts, OPTION_SKIP_GAMEINFO, TRUE, OPTION_PRIORITY_CMDLINE);
	options_set_bool(opts, OPTION_THROTTLE, FALSE, OPTION_PRIORITY_CMDLINE);
	options_set_bool(opts, OPTION_DEBUG, FALSE, OPTION_PRIORITY_CMDLINE);
	options_set_bool(opts, OPTION_DEBUG_INTERNAL, FALSE, OPTION_PRIORITY_CMDLINE);
	options_set_bool(opts, OPTION_WRITECONFIG, FALSE, OPTION_PRIORITY_CMDLINE);

	if (current_testcase.ram != 0)
	{
		options_set_int(opts, OPTION_RAMSIZE, current_testcase.ram, OPTION_PRIORITY_CMDLINE);
	}

	/* ugh... hideous ugly fake arguments */
	fake_argv[0] = "MESSTEST";
	fake_argv[1] = driver->name;
	options_parse_command_line(opts, ARRAY_LENGTH(fake_argv), (char **) fake_argv, OPTION_PRIORITY_CMDLINE,TRUE);

	/* preload any needed images */
	while(current_command->command_type == MESSTEST_COMMAND_IMAGE_PRELOAD)
	{
		/* get the path */
		fullpath = assemble_software_path(astring_alloc(), driver, current_command->u.image_args.filename);

		/* get the option name */
		device_opt = device_config_image_interface::device_typename(current_command->u.image_args.device_ident.type);

		/* set the option */
		options_set_string(opts, device_opt, astring_c(fullpath), OPTION_PRIORITY_CMDLINE);

		/* cleanup */
		astring_free(fullpath);
		fullpath = NULL;

		/* next command */
		current_command++;
	}

	/* perform the test */
	report_message(MSG_INFO, "Beginning test (driver '%s')", current_testcase.driver);
	begin_time = clock();
	mame_set_output_channel(OUTPUT_CHANNEL_ERROR, messtest_output_error, NULL, NULL, NULL);
	mame_set_output_channel(OUTPUT_CHANNEL_WARNING, mame_null_output_callback, NULL, NULL, NULL);
	mame_set_output_channel(OUTPUT_CHANNEL_INFO, mame_null_output_callback, NULL, NULL, NULL);
	mame_set_output_channel(OUTPUT_CHANNEL_DEBUG, mame_null_output_callback, NULL, NULL, NULL);
	mame_set_output_channel(OUTPUT_CHANNEL_LOG, mame_null_output_callback, NULL, NULL, NULL);
	test_osd_interface osd;
	mame_execute(osd, opts);
	real_run_time = ((double) (clock() - begin_time)) / CLOCKS_PER_SEC;

	/* what happened? */
	switch(state)
	{
		case STATE_ABORTED:
			report_message(MSG_FAILURE, "Test aborted");
			rc = MESSTEST_RESULT_RUNTIMEFAILURE;
			break;

		case STATE_DONE:
			if (had_failure)
			{
				report_message(MSG_FAILURE, "Test failed (real time %.2f; emu time %.2f [%i%%])",
					real_run_time, final_time.as_double(), (int) ((final_time.as_double() / real_run_time) * 100));
				rc = MESSTEST_RESULT_RUNTIMEFAILURE;
			}
			else
			{
				report_message(MSG_INFO, "Test succeeded (real time %.2f; emu time %.2f [%i%%])",
					real_run_time, final_time.as_double(), (int) ((final_time.as_double() / real_run_time) * 100));
				rc = MESSTEST_RESULT_SUCCESS;
			}
			break;

		default:
			state = STATE_ABORTED;
			report_message(MSG_FAILURE, "Abnormal termination");
			rc = MESSTEST_RESULT_STARTFAILURE;
			break;
	}

	if (results)
	{
		results->rc = rc;
		results->runtime_hash = runtime_hash;
	}

	options_free(opts);
	return rc;
}
コード例 #21
0
ファイル: main.c プロジェクト: simonproctor/edax-reversi
/**
 * @brief edax main function.
 *
 * Do a global initialization and choose a User Interface protocol.
 *
 * @param argc Number of arguments.
 * @param argv Command line arguments.
 */
int main(int argc, char **argv)
{
	UI *ui;
	int i, r, level = 0, size = 8;
	char *problem_file = NULL;
	char *wthor_file = NULL;
	char *count_type = NULL;
	int n_bench = 0;

	// options.n_task default to system cpu number
	options.n_task = get_cpu_number();

	// options from edax.ini
	options_parse("edax.ini");

	// allocate ui
	ui = (UI*) malloc(sizeof *ui);
	if (ui == NULL) fatal_error("Cannot allocate a user interface.\n");
	ui->type = UI_EDAX;
	ui->init = ui_init_edax;
	ui->free = ui_free_edax;
	ui->loop = ui_loop_edax;

	// parse arguments
	for (i = 1; i < argc; i++) {
		char *arg = argv[i];
		while (*arg == '-') ++arg;
		if (strcmp(arg, "v") == 0 || strcmp(arg, "version") == 0) version();
		else if (ui_switch(ui, arg)) ;
		else if ((r = (options_read(arg, argv[i + 1]))) > 0) i += r - 1;
		else if (strcmp(arg, "solve") == 0 && argv[i + 1]) problem_file = argv[++i];
		else if (strcmp(arg, "wtest") == 0 && argv[i + 1]) wthor_file = argv[++i];
		else if (strcmp(arg, "bench") == 0 && argv[i + 1]) n_bench = atoi(argv[++i]);
		else if (strcmp(arg, "count") == 0 && argv[i + 1]) {
			count_type = argv[++i];
			if (argv[i + 1]) level = string_to_int(argv[++i], 0);
			if (argv[i + 1] && strcmp(argv[i + 1], "6x6") == 0) {
				size = 6;
				++i;
			}
			
	
		}
		else usage();
	}
	options_bound();

	// initialize
	edge_stability_init();
	hash_code_init();
	hash_move_init();
	statistics_init();
	eval_open(options.eval_file);
	search_global_init();

	// solver & tester
	if (problem_file || wthor_file || n_bench) {
		Search search[1];
		search_init(search);
		search->options.header = " depth|score|       time   |  nodes (N)  |   N/s    | principal variation";
		search->options.separator = "------+-----+--------------+-------------+----------+---------------------";
		if (options.verbosity) version();
		if (problem_file) obf_test(search, problem_file, NULL);
		if (wthor_file) wthor_test(wthor_file, search);
		if (n_bench) obf_speed(search, n_bench);
		search_free(search);

	} else if (count_type){
		Board board[1];
		board_init(board);
		if (strcmp(count_type, "games") == 0) quick_count_games(board, level, size);		
		else if (strcmp(count_type, "positions") == 0) count_positions(board, level, size);		
		else if (strcmp(count_type, "shapes") == 0) count_shapes(board, level, size);		

	} else if (ui->type == UI_CASSIO) {
		engine_loop();

	// other protocols
	} else {
		ui_event_init(ui);
		ui->init(ui);
		ui->loop(ui);
		if (ui->free) ui->free(ui);
		ui_event_free(ui);
	}

	// display statistics
	statistics_print(stdout);


	// free;
	eval_close();
	options_free();
	free(ui);

	return 0;
}
コード例 #22
0
CTEST(node_serial_test, leaf_2_record)
{
	int ret = 0;
	int fd = ness_os_open(BRT_FILE, O_RDWR | O_CREAT, 0777);
	struct block *b = block_new();
	struct hdr *hdr = (struct hdr*)xcalloc(1, sizeof(*hdr));
	struct options *opts = options_new();

	/*
	 * dummy brt leaf
	 */
	uint64_t nid = 3;

	struct node *dummy_leaf = leaf_alloc_empty(nid);
	leaf_alloc_bsm(dummy_leaf);

	MSN msn = 0U;
	struct xids *xids = NULL;
	struct msg k, v;
	k.size = 6;
	k.data = "hello";
	v.size = 6;
	v.data = "world";
	basement_put(dummy_leaf->u.l.le->bsm, &k, &v, MSG_INSERT, msn, xids);

	struct msg k1, v1;
	k1.size = 6;
	k1.data = "hellx";
	v1.size = 6;
	v1.data = "worlx";
	basement_put(dummy_leaf->u.l.le->bsm, &k1, &v1, MSG_INSERT, msn, xids);

	ret = serialize_node_to_disk(fd, b, dummy_leaf, hdr);
	ASSERT_TRUE(ret > 0);

	//free
	node_free(dummy_leaf);

	struct node *dummy_leaf1;
	ret = deserialize_node_from_disk(fd, b, nid, &dummy_leaf1, 0);
	ASSERT_TRUE(ret > 0);

	ASSERT_EQUAL(2, basement_count(dummy_leaf1->u.l.le->bsm));

	struct basement_iter iter;
	basement_iter_init(&iter, dummy_leaf1->u.l.le->bsm);
	basement_iter_seek(&iter, &k);
	ASSERT_EQUAL(1, iter.valid);
	ASSERT_STR("world", iter.val.data);

	basement_iter_seek(&iter, &k1);
	ASSERT_EQUAL(1, iter.valid);
	ASSERT_STR("worlx", iter.val.data);

	//free
	node_free(dummy_leaf1);

	ness_os_close(fd);
	block_free(b);
	xfree(hdr);
	options_free(opts);
	xcheck_all_free();
}
コード例 #23
0
ファイル: main.c プロジェクト: oopsmonk/moc-git
int main (int argc, char *argv[])
{
	struct parameters params;
	lists_t_strs *deferred_overrides;
	lists_t_strs *args;

#ifdef HAVE_UNAME_SYSCALL
	int rc;
	struct utsname uts;
#endif

#ifdef PACKAGE_REVISION
	logit ("This is Music On Console (revision %s)", PACKAGE_REVISION);
#else
	logit ("This is Music On Console (version %s)", PACKAGE_VERSION);
#endif

#ifdef CONFIGURATION
	logit ("Configured:%s", CONFIGURATION);
#endif

#ifdef HAVE_UNAME_SYSCALL
	rc = uname (&uts);
	if (rc == 0)
		logit ("Running on: %s %s %s", uts.sysname, uts.release, uts.machine);
#endif

	log_command_line (argc, argv);

	files_init ();

	if (get_home () == NULL)
		fatal ("Could not determine user's home directory!");

	memset (&params, 0, sizeof(params));
	options_init ();
	deferred_overrides = lists_strs_new (4);

	/* set locale according to the environment variables */
	if (!setlocale(LC_ALL, ""))
		logit ("Could not set locale!");

	args = process_command_line (argc, argv, &params, deferred_overrides);

	if (params.dont_run_iface && params.only_server)
		fatal ("-c, -a and -p options can't be used with --server!");

	if (!params.config_file)
		params.config_file = xstrdup (create_file_name ("config"));
	options_parse (params.config_file);
	if (params.config_file)
		free (params.config_file);
	params.config_file = NULL;

	process_deferred_overrides (deferred_overrides);
	lists_strs_free (deferred_overrides);
	deferred_overrides = NULL;

	check_moc_dir ();

	io_init ();
	rcc_init ();
	decoder_init (params.debug);
	srand (time(NULL));

	if (!params.only_server && params.dont_run_iface)
		server_command (&params, args);
	else
		start_moc (&params, args);

	lists_strs_free (args);
	options_free ();
	decoder_cleanup ();
	io_cleanup ();
	rcc_cleanup ();
	files_cleanup ();
	compat_cleanup ();

	exit (EXIT_SUCCESS);
}
コード例 #24
0
ファイル: main.c プロジェクト: crowja/fqutils
int
main( int argc, char *argv[] )
{
   FILE       *out_a, *out_b;
   char       *h1, *h2, *s, *q;
   char       *id = NULL;
   char       *outname_a = NULL, *outname_b = NULL, *outdirname = NULL;
   int         i;
   struct options *o = options_new(  );
   struct tokenset *t = tokenset_new(  );
   struct fqreader *fq = fqreader_new( NULL );

   /* Get the command line options */
   options_cmdline( o, argc, argv );

   if ( _IS_NULL( o->outname ) || strlen( o->outname ) == 0 ) {
      o->outname = realloc( o->outname, 4 * sizeof ( char ) );
      strcpy( o->outname, "FQU" );
   }

   /* Create the output directory if necessary */
   outdirname = realloc( outdirname, sizeof ( char ) * ( 2 + strlen( o->outname ) ) );
   strcpy( outdirname, o->outname );
   if ( strchr( outdirname, '/' ) ) {            /* not the current directory */
      dirname( outdirname );
      mkdirp( outdirname, S_IRWXU | S_IRWXG | S_IRWXO );
   }


   /* Read the id files */
   for ( i = o->optind; i < argc; i++ ) {

      char       *line;
      struct linereader *z = linereader_new(  );

      linereader_init( z, argv[i] );

      if ( _IS_NULL( z ) ) {
         fprintf( stderr, "[ERROR] %s: Cannot open input file \"%s\"\n", _I_AM, argv[i] );
         exit( 1 );
      }

      while ( ( line = ( char * ) linereader_next( z ) ) ) {
         unsigned    len;

         stru_trim( line );

         if ( line[0] == '#' || stru_is_ws( line ) )
            continue;

         len = strcspn( line, "\f\n\r\t\v " );
         line[len] = '\0';

         tokenset_add( t, line );
      }

      linereader_free( z );
   }

   outname_a = realloc( outname_a, sizeof ( char ) * ( 6 + strlen( o->outname ) ) );
   strcpy( outname_a, o->outname );
   strcat( outname_a, "_A.fq" );
   out_a = fopen( outname_a, "wb" );
   if ( _IS_NULL( out_a ) ) {
      fprintf( stderr, "Could not open first output file \"%s\"\n", outname_a );
      exit( 1 );
   }

   outname_b = realloc( outname_b, sizeof ( char ) * ( 6 + strlen( o->outname ) ) );
   strcpy( outname_b, o->outname );
   strcat( outname_b, "_B.fq" );
   out_b = fopen( outname_b, "wb" );
   if ( _IS_NULL( out_b ) ) {
      fprintf( stderr, "Could not open second output file \"%s\"\n", outname_b );
      exit( 1 );
   }


   while ( fqreader_next( fq, &h1, &h2, &s, &q ) ) {

      utils_extract_id( &id, h1 );               /* get the identifier from header 1 */

      if ( tokenset_exists( t, id ) )
         fprintf( out_a, "@%s\n%s\n+%s\n%s\n", h1, s, h2, q );

      else
         fprintf( out_b, "@%s\n%s\n+%s\n%s\n", h1, s, h2, q );
   }

   fclose( out_a );
   fclose( out_b );

   _FREE( id );
   _FREE( outname_a );
   _FREE( outname_b );
   fqreader_free( fq );
   options_free( o );
   tokenset_free( t );

   return 0;
}
コード例 #25
0
ファイル: main.c プロジェクト: crowja/fqutils
int
main( int argc, char *argv[] )
{
   char       *h1, *h2, *s, *q;
   unsigned    i;
   unsigned    n;
   struct options *o = options_new(  );
   struct fqreader *z;

   /* Get the command line options */
   options_cmdline( o, argc, argv );

   words = tokenset_new(  );
   word = realloc( word, sizeof ( char ) * ( 1 + o->word_size ) );

   if ( o->optind == argc ) {                    /* read from stdin */

      z = fqreader_new( NULL );

      while ( fqreader_next( z, &h1, &h2, &s, &q ) ) {
         stru_toupper( s );
         _update_table( o->word_size, s, o->check_initial );
      }

      fqreader_free( z );
   }

   else {                                        /* read from input files */
      int         k;

      for ( k = o->optind; k < argc; k++ ) {

         z = fqreader_new( argv[k] );

         if ( _IS_NULL( z ) ) {
            fprintf( stderr, "[ERROR] %s: Cannot open input file \"%s\"\n", _I_AM, argv[k] );
            exit( 1 );
         }

         while ( fqreader_next( z, &h1, &h2, &s, &q ) ) {
            stru_toupper( s );
            _update_table( o->word_size, s, o->check_initial );
         }

         fqreader_free( z );
      }
   }

   /* Print the countlist */

   n = tokenset_count( words );

   for ( i = 0; i < n; i++ ) {
      if ( countlist[i].count < o->min_count )
         continue;
      printf( "%s\t%d\n", tokenset_get_by_id( words, countlist[i].id ), countlist[i].count );
   }

   options_free( o );
   tokenset_free( words );
   _FREE( word );
   _FREE( countlist );

   return 0;
}
コード例 #26
0
ファイル: clifront.c プロジェクト: cdenix/ps3-mame-0125
int cli_execute(int argc, char **argv, const options_entry *osd_options)
{
	core_options *options;
	astring *gamename = astring_alloc();
	astring *exename = astring_alloc();
	const char *gamename_option;
	const game_driver *driver;
	int result;

	/* initialize the options manager and add the CLI-specific options */
	options = mame_options_init(osd_options);
	options_add_entries(options, cli_options);

	/* parse the command line first; if we fail here, we're screwed */
	if (options_parse_command_line(options, argc, argv, OPTION_PRIORITY_CMDLINE))
	{
		result = MAMERR_INVALID_CONFIG;
		goto error;
	}

	/* parse the simple commmands before we go any further */
	core_filename_extract_base(exename, argv[0], TRUE);

	result = execute_simple_commands(options, astring_c(exename));
	if (result != -1) {
		goto error;
	}

	/* find out what game we might be referring to */
	gamename_option = options_get_string(options, OPTION_GAMENAME);

	core_filename_extract_base(gamename, gamename_option, TRUE);

	driver = driver_get_name(astring_c(gamename));

	/* execute any commands specified */
	result = execute_commands(options, astring_c(exename), driver);
	if (result != -1) {
		goto error;
	}

	/* if we don't have a valid driver selected, offer some suggestions */
	if (strlen(gamename_option) > 0 && driver == NULL)
	{
		const game_driver *matches[10];
		int drvnum;

		/* get the top 10 approximate matches */
		driver_list_get_approx_matches(drivers, gamename_option, ARRAY_LENGTH(matches), matches);

		/* print them out */
		fprintf(stderr, "\n\"%s\" approximately matches the following\n"
				"supported " GAMESNOUN " (best match first):\n\n", gamename_option);
		for (drvnum = 0; drvnum < ARRAY_LENGTH(matches); drvnum++)
			if (matches[drvnum] != NULL)
				fprintf(stderr, "%-10s%s\n", matches[drvnum]->name, matches[drvnum]->description);

		/* exit with an error */
		result = MAMERR_NO_SUCH_GAME;
		goto error;
	}
	/* run the game */
	result = mame_execute(options);

error:
	/* free our options and exit */
	options_free(options);
	astring_free(gamename);
	astring_free(exename);
	return result;
}
コード例 #27
0
ファイル: main.c プロジェクト: collinanderson/cptutils
int main(int argc,char** argv)
{
  struct gengetopt_args_info info;
  cptcat_opt_t opt = {0};

  /* use gengetopt */

  if (options(argc, argv, &info) != 0)
    {
      fprintf(stderr,"failed to parse command line\n");
      return EXIT_FAILURE;
    }

  /* check arguments & transfer to opt structure */ 

  opt.verbose = info.verbose_given;

  opt.output = (info.output_given ? info.output_arg : NULL);

  if (!opt.output && opt.verbose)
    {
      fprintf(stderr,"verbosity suppressed (<stdout> for results)\n");
      opt.verbose = 0;
    }

  if (info.inputs_num < 2)
    {
      fprintf(stderr,"at least 2 input files required\n");
      return EXIT_FAILURE;
    }

  opt.input.n    = info.inputs_num; 
  opt.input.file = (const char**)info.inputs;
  
  if (opt.verbose)
    printf("This is cptcat (version %s)\n",VERSION);

  btrace_enable("cptcat");

  int err = cptcat(opt);

  if (err)
    {
      btrace("failed (error %i)", err);
      btrace_print_stream(stderr, BTRACE_PLAIN);

      if (info.backtrace_file_given)
        {
          int format = BTRACE_XML;
          if (info.backtrace_format_given)
            {
              format = btrace_format(info.backtrace_format_arg);
              if (format == BTRACE_ERROR)
                {
                  fprintf(stderr, "no such backtrace format %s\n", 
                          info.backtrace_format_arg);
                  return EXIT_FAILURE;
                }
            }     
          btrace_print(info.backtrace_file_arg, format);
        }
    }

  btrace_reset();
  btrace_disable();

  if (opt.verbose)
    printf("done.\n");

  options_free(&info);

  return (err ? EXIT_FAILURE : EXIT_SUCCESS);
}
コード例 #28
0
ファイル: vecsum.c プロジェクト: simonzhangsm/CDH5.1.x
/*
 * vecsum is a microbenchmark which measures the speed of various ways of
 * reading from HDFS.  It creates a file containing floating-point 'doubles',
 * and computes the sum of all the doubles several times.  For some CPUs,
 * assembly optimizations are used for the summation (SSE, etc).
 */
int main(void)
{
    int ret = 1;
    struct options *opts = NULL;
    struct local_data *cdata = NULL;
    struct libhdfs_data *ldata = NULL;
    struct stopwatch *watch = NULL;

    if (check_byte_size(VECSUM_CHUNK_SIZE, "VECSUM_CHUNK_SIZE") ||
        check_byte_size(ZCR_READ_CHUNK_SIZE,
                "ZCR_READ_CHUNK_SIZE") ||
        check_byte_size(NORMAL_READ_CHUNK_SIZE,
                "NORMAL_READ_CHUNK_SIZE")) {
        goto done;
    }
    opts = options_create();
    if (!opts)
        goto done;
    if (opts->ty == VECSUM_LOCAL) {
        cdata = local_data_create(opts);
        if (!cdata)
            goto done;
    } else {
        ldata = libhdfs_data_create(opts);
        if (!ldata)
            goto done;
    }
    watch = stopwatch_create();
    if (!watch)
        goto done;
    switch (opts->ty) {
    case VECSUM_LOCAL:
        vecsum_local(cdata, opts);
        ret = 0;
        break;
    case VECSUM_LIBHDFS:
        ret = vecsum_libhdfs(ldata, opts);
        break;
    case VECSUM_ZCR:
        ret = vecsum_zcr(ldata, opts);
        break;
    }
    if (ret) {
        fprintf(stderr, "vecsum failed with error %d\n", ret);
        goto done;
    }
    ret = 0;
done:
    fprintf(stderr, "cleaning up...\n");
    if (watch && (ret == 0)) {
        long long length = vecsum_length(opts, ldata);
        if (length >= 0) {
            stopwatch_stop(watch, length * opts->passes);
        }
    }
    if (cdata)
        local_data_free(cdata);
    if (ldata)
        libhdfs_data_free(ldata);
    if (opts)
        options_free(opts);
    return ret;
}
コード例 #29
0
ファイル: main.c プロジェクト: panzhengyang/cptutils
int main(int argc, char** argv)
{
  struct gengetopt_args_info info;
  char *infile = NULL, *outfile = NULL;
  gimpsvg_opt_t opt = {0};

  /* use gengetopt */

  if (options(argc, argv, &info) != 0)
    {
      fprintf(stderr, "failed to parse command line\n");
      return EXIT_FAILURE;
    }

  /* check arguments & transfer to opt structure */ 

  opt.verbose = info.verbose_given;
  opt.reverse = false;

  if ((opt.samples = info.samples_arg) < SAMPLES_MIN)
    {
      fprintf(stderr, "at least %i samples required\n", SAMPLES_MIN);
      opt.samples = SAMPLES_MIN;
    }

  /* handle preview */

  if (info.preview_flag || info.geometry_given)
    {
      opt.preview.use = true;
      if (svg_preview_geometry(info.geometry_arg, &(opt.preview)) != 0)
        {
          fprintf(stderr, "failed parse of geometry : %s\n", 
                  info.geometry_arg);
          return EXIT_FAILURE;
        }
    }
  else
    opt.preview.use = false;
  
  /* null outfile for stdout */

  outfile = (info.output_given ? info.output_arg : NULL);

  if (!outfile && opt.verbose)
    {
      fprintf(stderr, "verbosity suppressed (<stdout> for results)\n");
      opt.verbose = 0;
    }

  /* null infile for stdin */

  switch (info.inputs_num)
    {
    case 0:
      infile = NULL;
      break;
    case 1:
      infile = info.inputs[0];
      break;
    default:
      fprintf(stderr, "Sorry, only one file at a time\n");
      return EXIT_FAILURE;
    }
  
  if (opt.verbose)
    printf("This is gimpsvg (version %s)\n", VERSION);

  svg_srand();

  btrace_enable("gimpsvg");

  int err = gimpsvg(infile, outfile, opt);

  if (err)
    {
      btrace("failed (error %i)", err);
      btrace_print_stream(stderr, BTRACE_PLAIN);

      if (info.backtrace_file_given)
	{
	  int format = BTRACE_XML;
	  if (info.backtrace_format_given)
	    {
	      format = btrace_format(info.backtrace_format_arg);
	      if (format == BTRACE_ERROR)
		{
		  fprintf(stderr, "no such backtrace format %s\n", 
			  info.backtrace_format_arg);
		  return EXIT_FAILURE;
		}
	    }	  
	  btrace_print(info.backtrace_file_arg, format);
	}
    }
  else if (opt.verbose)
    {
      printf("palette written to %s\n", (outfile ? outfile : "<stdin>"));
      if (opt.preview.use)
	{
	  printf("with preview (%zu x %zu px)\n", 
		 opt.preview.width, 
		 opt.preview.height);
	}
    }

  btrace_reset();
  btrace_disable();

  if (opt.verbose)
    printf("done.\n");

  options_free(&info);

  return (err ? EXIT_FAILURE : EXIT_SUCCESS);
}