Ejemplo n.º 1
0
void verlet(const char* filename){
dictionary* ini;
    ini = iniparser_load(filename);

    iniparser_dump(ini, stdout);
    FILE *file;
    file = fopen(LOGFILE, "a");
    iniparser_dump(ini, file);
    fclose(file);
    ReportMessage("\n");

    t_key       key  = key_init(ini);
    t_pSys      pSys = pSys_init (ini);
    t_opts      opts = opts_init (ini);
    t_pair      p    = t_pair_init(ini);
    t_dump      dump = dump_init(ini);
    t_fix       fix  = fix_init(ini);
    t_compute   compute = compute_init(ini, &key);

    init (&key, &pSys, &opts, &p, &compute);
    if(key.dump) dump_run(&key, &pSys, &opts, &dump); // Make initial snapshot.
    while(opts.thisIter < opts.targIters){  // Repeat until iterational limit.
        verlet_iter (&key, &pSys, &opts, &p, &fix, &compute);
        if(key.dump) dump_run(&key, &pSys, &opts, &dump);
        resetStep(&pSys);
    }
}
Ejemplo n.º 2
0
int main(int argc, char **argv) {
	opts_init();

	CU_pSuite maildir_suite = NULL;
	CU_pSuite regexp_suite = NULL;
	CU_pSuite fsm_suite = NULL;

	if (CU_initialize_registry() != CUE_SUCCESS) goto exit;

	if (!(maildir_suite = CU_add_suite("Test maildir.", init_maildir_suite, clean_maildir_suite))) goto clean;
	for (int i = 0; i < sizeof(maildir_tests) / sizeof(struct test); ++i) {
		if (!CU_add_test(maildir_suite, maildir_tests[i].name, maildir_tests[i].func)) goto clean;
	}

	if (!(regexp_suite = CU_add_suite("Test regexp.", init_regexp_suite, clean_regexp_suite))) goto clean;
	for (int i = 0; i < sizeof(regexp_tests) / sizeof(struct test); ++i) {
		if (!CU_add_test(regexp_suite, regexp_tests[i].name, regexp_tests[i].func)) goto clean;
	}

	if (!(fsm_suite = CU_add_suite("Test FSM.", init_fsm_suite, clean_fsm_suite))) goto clean;
	for (int i = 0; i < sizeof(fsm_tests) / sizeof(struct test); ++i) {
		if (!CU_add_test(fsm_suite, fsm_tests[i].name, fsm_tests[i].func)) goto clean;
	}

	CU_basic_set_mode(CU_BRM_VERBOSE);
	CU_basic_run_tests();

clean:
	CU_cleanup_registry();
exit:
	opts_final();
	return CU_get_error();
}
Ejemplo n.º 3
0
/*
 * test main for conf module, usage: a.out conffile
 */
int
main(int argc, char *argv[])
{
	struct opts *opts;

	err_init(argv[0]);
	setbuf(stdout, NULL);
	opts_init(Opttable, Opttable_cnt);

	opts = opts_parse(NULL, NULL, 0);

	if (argc != 2)
		err(EF_RAW, "usage: %s conffile\n", argv[0]);

	conf_open(argv[1], argv[1], opts);

	printf("conffile <%s>:\n", argv[1]);
	conf_print(stdout, NULL);

	conf_close(opts);

	err_done(0);
	/* NOTREACHED */
	return (0);
}
Ejemplo n.º 4
0
int main(int argc, char **argv) {
    opts_init(argc, argv);
    struct scheduler s;
    s.in = fopen(opts.in_file_name, "r");
    if (!s.in) {
        perror(opts.in_file_name);
        return 1;
    }
    s.out = stdout;
    return scheduler(&s);
}
Ejemplo n.º 5
0
tc_api_task
tc_api_task_init(const char *op)
{
	tc_api_task task = NULL;
	int fail = 1;

	if ((task = alloc_safe_mem(sizeof(*task))) == NULL) {
		errno = ENOMEM;
		goto out;
	}

	if ((task->opts = opts_init()) == NULL) {
		errno = ENOMEM;
		goto out;
	}

	if (_match(op, "create")) {
		task->op = TC_OP_CREATE;
	} else if (_match(op, "map")) {
		task->op = TC_OP_MAP;
	} else if (_match(op, "unmap")) {
		task->op = TC_OP_UNMAP;
	} else if (_match(op, "info")) {
		task->op = TC_OP_INFO;
	} else if (_match(op, "info_mapped")) {
		task->op = TC_OP_INFO_MAPPED;
	} else if (_match(op, "modify")) {
		task->op = TC_OP_MODIFY;
	} else if (_match(op, "restore")) {
		task->op = TC_OP_RESTORE;
	} else {
		errno = EINVAL;
		goto out;
	}

	tc_set_iteration_count(0);

	fail = 0;

out:
	if (fail && task != NULL) {
		if (task->opts != NULL)
			opts_free(task->opts);
		free_safe_mem(task);
	}

	return fail ? NULL : task;
}
Ejemplo n.º 6
0
int  main (int argc, char **argv){ // {{{
	int c;
	int option_index;
	opt_func func;
	
	opts_init();
	
	option_index = -1;
	while( (c = getopt_long (argc, argv, short_options, long_options, &option_index)) != -1){
		struct cmdline_option *mopt;
		
		if(option_index == -1){
			mopt = map_opts[c - 32];
		}else{
			mopt = &option_data[ long_options[option_index].val ];
		}
		if(mopt == NULL)
			exit(255);
		
		switch(mopt->type){
			case OPT_VALUE_INT:
				*(unsigned int *)(mopt->opt_ptr) = atoi(optarg);
				break;
			case OPT_VALUE_STR:
				*(char **)       (mopt->opt_ptr) = strdup(optarg);
				break;
			case OPT_VALUE_BOOL:
				*(unsigned int *)(mopt->opt_ptr) = 1;
				break;
			case OPT_GROUP:
				break;
			case OPT_FUNC:
				func = (opt_func)(mopt->opt_ptr);
				func();
				exit(0);
		}
		
		option_index = -1;
	}
	
	main_rest();
	main_cleanup();	
	
	return 0;
} // }}}
Ejemplo n.º 7
0
Archivo: main.c Proyecto: lichray/nvi2
/*
 * editor --
 *	Main editor routine.
 *
 * PUBLIC: int editor(GS *, int, char *[]);
 */
int
editor(GS *gp, int argc, char *argv[])
{
	extern int optind;
	extern char *optarg;
	const char *p;
	EVENT ev;
	FREF *frp;
	SCR *sp;
	size_t len;
	u_int flags;
	int ch, flagchk, lflag, secure, startup, readonly, rval, silent;
	char *tag_f, *wsizearg, path[256];
	CHAR_T *w;
	size_t wlen;

	/* Initialize the busy routine, if not defined by the screen. */
	if (gp->scr_busy == NULL)
		gp->scr_busy = vs_busy;
	/* Initialize the message routine, if not defined by the screen. */
	if (gp->scr_msg == NULL)
		gp->scr_msg = vs_msg;
	gp->catd = (nl_catd)-1;

	/* Common global structure initialization. */
	TAILQ_INIT(gp->dq);
	TAILQ_INIT(gp->hq);
	SLIST_INIT(gp->ecq);
	SLIST_INSERT_HEAD(gp->ecq, &gp->excmd, q);
	gp->noprint = DEFAULT_NOPRINT;

	/* Structures shared by screens so stored in the GS structure. */
	TAILQ_INIT(gp->frefq);
	TAILQ_INIT(gp->dcb_store.textq);
	SLIST_INIT(gp->cutq);
	SLIST_INIT(gp->seqq);

	/* Set initial screen type and mode based on the program name. */
	readonly = 0;
	if (!strcmp(getprogname(), "ex") || !strcmp(getprogname(), "nex"))
		LF_INIT(SC_EX);
	else {
		/* Nview, view are readonly. */
		if (!strcmp(getprogname(), "nview") ||
		    !strcmp(getprogname(), "view"))
			readonly = 1;
		
		/* Vi is the default. */
		LF_INIT(SC_VI);
	}

	/* Convert old-style arguments into new-style ones. */
	if (v_obsolete(argv))
		return (1);

	/* Parse the arguments. */
	flagchk = '\0';
	tag_f = wsizearg = NULL;
	lflag = secure = silent = 0;
	startup = 1;

	/* Set the file snapshot flag. */
	F_SET(gp, G_SNAPSHOT);

#ifdef DEBUG
	while ((ch = getopt(argc, argv, "c:D:eFlRrSsT:t:vw:")) != EOF)
#else
	while ((ch = getopt(argc, argv, "c:eFlRrSst:vw:")) != EOF)
#endif
		switch (ch) {
		case 'c':		/* Run the command. */
			/*
			 * XXX
			 * We should support multiple -c options.
			 */
			if (gp->c_option != NULL) {
				warnx("only one -c command may be specified.");
				return (1);
			}
			gp->c_option = optarg;
			break;
#ifdef DEBUG
		case 'D':
			switch (optarg[0]) {
			case 's':
				startup = 0;
				break;
			case 'w':
				attach(gp);
				break;
			default:
				warnx("usage: -D requires s or w argument.");
				return (1);
			}
			break;
#endif
		case 'e':		/* Ex mode. */
			LF_CLR(SC_VI);
			LF_SET(SC_EX);
			break;
		case 'F':		/* No snapshot. */
			F_CLR(gp, G_SNAPSHOT);
			break;
		case 'l':		/* Set lisp, showmatch options. */
			lflag = 1;
			break;
		case 'R':		/* Readonly. */
			readonly = 1;
			break;
		case 'r':		/* Recover. */
			if (flagchk == 't') {
				warnx("only one of -r and -t may be specified.");
				return (1);
			}
			flagchk = 'r';
			break;
		case 'S':
			secure = 1;
			break;
		case 's':
			silent = 1;
			break;
#ifdef DEBUG
		case 'T':		/* Trace. */
			if ((gp->tracefp = fopen(optarg, "w")) == NULL) {
				warn("%s", optarg);
				goto err;
			}
			(void)fprintf(gp->tracefp,
			    "\n===\ntrace: open %s\n", optarg);
			break;
#endif
		case 't':		/* Tag. */
			if (flagchk == 'r') {
				warnx("only one of -r and -t may be specified.");
				return (1);
			}
			if (flagchk == 't') {
				warnx("only one tag file may be specified.");
				return (1);
			}
			flagchk = 't';
			tag_f = optarg;
			break;
		case 'v':		/* Vi mode. */
			LF_CLR(SC_EX);
			LF_SET(SC_VI);
			break;
		case 'w':
			wsizearg = optarg;
			break;
		case '?':
		default:
			(void)gp->scr_usage();
			return (1);
		}
	argc -= optind;
	argv += optind;

	/*
	 * -s option is only meaningful to ex.
	 *
	 * If not reading from a terminal, it's like -s was specified.
	 */
	if (silent && !LF_ISSET(SC_EX)) {
		warnx("-s option is only applicable to ex.");
		goto err;
	}
	if (LF_ISSET(SC_EX) && F_ISSET(gp, G_SCRIPTED))
		silent = 1;

	/*
	 * Build and initialize the first/current screen.  This is a bit
	 * tricky.  If an error is returned, we may or may not have a
	 * screen structure.  If we have a screen structure, put it on a
	 * display queue so that the error messages get displayed.
	 *
	 * !!!
	 * Everything we do until we go interactive is done in ex mode.
	 */
	if (screen_init(gp, NULL, &sp)) {
		if (sp != NULL)
			TAILQ_INSERT_HEAD(gp->dq, sp, q);
		goto err;
	}
	F_SET(sp, SC_EX);
	TAILQ_INSERT_HEAD(gp->dq, sp, q);

	if (v_key_init(sp))		/* Special key initialization. */
		goto err;

	{ int oargs[5], *oargp = oargs;
	if (lflag) {			/* Command-line options. */
		*oargp++ = O_LISP;
		*oargp++ = O_SHOWMATCH;
	}
	if (readonly)
		*oargp++ = O_READONLY;
	if (secure)
		*oargp++ = O_SECURE;
	*oargp = -1;			/* Options initialization. */
	if (opts_init(sp, oargs))
		goto err;
	}
	if (wsizearg != NULL) {
		ARGS *av[2], a, b;
		(void)snprintf(path, sizeof(path), "window=%s", wsizearg);
		a.bp = (CHAR_T *)path;
		a.len = strlen(path);
		b.bp = NULL;
		b.len = 0;
		av[0] = &a;
		av[1] = &b;
		(void)opts_set(sp, av, NULL);
	}
	if (silent) {			/* Ex batch mode option values. */
		O_CLR(sp, O_AUTOPRINT);
		O_CLR(sp, O_PROMPT);
		O_CLR(sp, O_VERBOSE);
		O_CLR(sp, O_WARN);
		F_SET(sp, SC_EX_SILENT);
	}

	sp->rows = O_VAL(sp, O_LINES);	/* Make ex formatting work. */
	sp->cols = O_VAL(sp, O_COLUMNS);

	if (!silent && startup) {	/* Read EXINIT, exrc files. */
		if (ex_exrc(sp))
			goto err;
		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
			if (screen_end(sp))
				goto err;
			goto done;
		}
	}

	/*
	 * List recovery files if -r specified without file arguments.
	 * Note, options must be initialized and startup information
	 * read before doing this.
	 */
	if (flagchk == 'r' && argv[0] == NULL) {
		if (rcv_list(sp))
			goto err;
		if (screen_end(sp))
			goto err;
		goto done;
	}

	/*
	 * !!!
	 * Initialize the default ^D, ^U scrolling value here, after the
	 * user has had every opportunity to set the window option.
	 *
	 * It's historic practice that changing the value of the window
	 * option did not alter the default scrolling value, only giving
	 * a count to ^D/^U did that.
	 */
	sp->defscroll = (O_VAL(sp, O_WINDOW) + 1) / 2;

	/*
	 * If we don't have a command-line option, switch into the right
	 * editor now, so that we position default files correctly, and
	 * so that any tags file file-already-locked messages are in the
	 * vi screen, not the ex screen.
	 *
	 * XXX
	 * If we have a command-line option, the error message can end
	 * up in the wrong place, but I think that the combination is
	 * unlikely.
	 */
	if (gp->c_option == NULL) {
		F_CLR(sp, SC_EX | SC_VI);
		F_SET(sp, LF_ISSET(SC_EX | SC_VI));
	}

	/* Open a tag file if specified. */
	if (tag_f != NULL) {
		CHAR2INT(sp, tag_f, strlen(tag_f) + 1, w, wlen);
		if (ex_tag_first(sp, w))
			goto err;
	}

	/*
	 * Append any remaining arguments as file names.  Files are recovery
	 * files if -r specified.  If the tag option or ex startup commands
	 * loaded a file, then any file arguments are going to come after it.
	 */
	if (*argv != NULL) {
		if (sp->frp != NULL) {
			/* Cheat -- we know we have an extra argv slot. */
			*--argv = strdup(sp->frp->name);
			if (*argv == NULL) {
				warn(NULL);
				goto err;
			}
		}
		sp->argv = sp->cargv = argv;
		F_SET(sp, SC_ARGNOFREE);
		if (flagchk == 'r')
			F_SET(sp, SC_ARGRECOVER);
	}

	/*
	 * If the ex startup commands and or/the tag option haven't already
	 * created a file, create one.  If no command-line files were given,
	 * use a temporary file.
	 */
	if (sp->frp == NULL) {
		if (sp->argv == NULL) {
			if ((frp = file_add(sp, NULL)) == NULL)
				goto err;
		} else  {
			if ((frp = file_add(sp, sp->argv[0])) == NULL)
				goto err;
			if (F_ISSET(sp, SC_ARGRECOVER))
				F_SET(frp, FR_RECOVER);
		}

		if (file_init(sp, frp, NULL, 0))
			goto err;
		if (EXCMD_RUNNING(gp)) {
			(void)ex_cmd(sp);
			if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
				if (screen_end(sp))
					goto err;
				goto done;
			}
		}
	}

	/*
	 * Check to see if we need to wait for ex.  If SC_SCR_EX is set, ex
	 * was forced to initialize the screen during startup.  We'd like to
	 * wait for a single character from the user, but we can't because
	 * we're not in raw mode.  We can't switch to raw mode because the
	 * vi initialization will switch to xterm's alternate screen, causing
	 * us to lose the messages we're pausing to make sure the user read.
	 * So, wait for a complete line.  
	 */
	if (F_ISSET(sp, SC_SCR_EX)) {
		p = msg_cmsg(sp, CMSG_CONT_R, &len);
		(void)write(STDOUT_FILENO, p, len);
		for (;;) {
			if (v_event_get(sp, &ev, 0, 0))
				goto err;
			if (ev.e_event == E_INTERRUPT ||
			    (ev.e_event == E_CHARACTER &&
			     (ev.e_value == K_CR || ev.e_value == K_NL)))
				break;
			(void)gp->scr_bell(sp);
		}
	}

	/* Switch into the right editor, regardless. */
	F_CLR(sp, SC_EX | SC_VI);
	F_SET(sp, LF_ISSET(SC_EX | SC_VI) | SC_STATUS_CNT);

	/*
	 * Main edit loop.  Vi handles split screens itself, we only return
	 * here when switching editor modes or restarting the screen.
	 */
	while (sp != NULL)
		if (F_ISSET(sp, SC_EX) ? ex(&sp) : vi(&sp))
			goto err;

done:	rval = 0;
	if (0)
err:		rval = 1;

	/* Clean out the global structure. */
	v_end(gp);

	return (rval);
}
Ejemplo n.º 8
0
Archivo: main.c Proyecto: fishman/nvi
/*
 * editor --
 *	Main editor routine.
 *
 * PUBLIC: int editor __P((WIN *, int, char *[]));
 */
int
editor(WIN *wp, int argc, char **argv)
{
	extern int optind;
	extern char *optarg;
	const char *p;
	EVENT ev;
	FREF *frp;
	SCR *sp;
	GS *gp;
	size_t len;
	u_int flags;
	int ch, flagchk, lflag, secure, startup, readonly, rval, silent;
	char *tag_f, *wsizearg, path[256];
	CHAR_T *w;
	size_t wlen;

	gp = wp->gp;

	/* Initialize the busy routine, if not defined by the screen. */
	if (gp->scr_busy == NULL)
		gp->scr_busy = vs_busy;
	/* Initialize the message routine, if not defined by the screen. */
	if (wp->scr_msg == NULL)
		wp->scr_msg = vs_msg;

	/* Set initial screen type and mode based on the program name. */
	readonly = 0;
	if (!strcmp(gp->progname, "ex") || !strcmp(gp->progname, "nex"))
		LF_INIT(SC_EX);
	else {
		/* Nview, view are readonly. */
		if (!strcmp(gp->progname, "nview") ||
		    !strcmp(gp->progname, "view"))
			readonly = 1;
		
		/* Vi is the default. */
		LF_INIT(SC_VI);
	}

	/* Convert old-style arguments into new-style ones. */
	if (v_obsolete(gp->progname, argv))
		return (1);

	/* Parse the arguments. */
	flagchk = '\0';
	tag_f = wsizearg = NULL;
	lflag = secure = silent = 0;
	startup = 1;

	/* Set the file snapshot flag. */
	F_SET(gp, G_SNAPSHOT);

#ifdef DEBUG
	while ((ch = getopt(argc, argv, "c:D:eFlRrSsT:t:vw:")) != EOF)
#else
	while ((ch = getopt(argc, argv, "c:eFlRrSst:vw:")) != EOF)
#endif
		switch (ch) {
		case 'c':		/* Run the command. */
			/*
			 * XXX
			 * We should support multiple -c options.
			 */
			if (gp->c_option != NULL) {
				v_estr(gp->progname, 0,
				    "only one -c command may be specified.");
				return (1);
			}
			gp->c_option = optarg;
			break;
#ifdef DEBUG
		case 'D':
			switch (optarg[0]) {
			case 's':
				startup = 0;
				break;
			case 'w':
				attach(gp);
				break;
			default:
				v_estr(gp->progname, 0,
				    "usage: -D requires s or w argument.");
				return (1);
			}
			break;
#endif
		case 'e':		/* Ex mode. */
			LF_CLR(SC_VI);
			LF_SET(SC_EX);
			break;
		case 'F':		/* No snapshot. */
			v_estr(gp->progname, 0, 
			    "-F option no longer supported.");
			break;
		case 'l':		/* Set lisp, showmatch options. */
			lflag = 1;
			break;
		case 'R':		/* Readonly. */
			readonly = 1;
			break;
		case 'r':		/* Recover. */
			if (flagchk == 't') {
				v_estr(gp->progname, 0,
				    "only one of -r and -t may be specified.");
				return (1);
			}
			flagchk = 'r';
			break;
		case 'S':
			secure = 1;
			break;
		case 's':
			silent = 1;
			break;
#ifdef TRACE
		case 'T':		/* Trace. */
			(void)vtrace_init(optarg);
			break;
#endif
		case 't':		/* Tag. */
			if (flagchk == 'r') {
				v_estr(gp->progname, 0,
				    "only one of -r and -t may be specified.");
				return (1);
			}
			if (flagchk == 't') {
				v_estr(gp->progname, 0,
				    "only one tag file may be specified.");
				return (1);
			}
			flagchk = 't';
			tag_f = optarg;
			break;
		case 'v':		/* Vi mode. */
			LF_CLR(SC_EX);
			LF_SET(SC_VI);
			break;
		case 'w':
			wsizearg = optarg;
			break;
		case '?':
		default:
			(void)gp->scr_usage();
			return (1);
		}
	argc -= optind;
	argv += optind;

	/*
	 * -s option is only meaningful to ex.
	 *
	 * If not reading from a terminal, it's like -s was specified.
	 */
	if (silent && !LF_ISSET(SC_EX)) {
		v_estr(gp->progname, 0, "-s option is only applicable to ex.");
		goto err;
	}
	if (LF_ISSET(SC_EX) && F_ISSET(gp, G_SCRIPTED))
		silent = 1;

	/*
	 * Build and initialize the first/current screen.  This is a bit
	 * tricky.  If an error is returned, we may or may not have a
	 * screen structure.  If we have a screen structure, put it on a
	 * display queue so that the error messages get displayed.
	 *
	 * !!!
	 * Everything we do until we go interactive is done in ex mode.
	 */
	if (screen_init(gp, NULL, &sp)) {
		if (sp != NULL) {
			CIRCLEQ_INSERT_HEAD(&wp->scrq, sp, q);
			sp->wp = wp;
		}
		goto err;
	}
	F_SET(sp, SC_EX);
	CIRCLEQ_INSERT_HEAD(&wp->scrq, sp, q);
	sp->wp = wp;

	if (v_key_init(sp))		/* Special key initialization. */
		goto err;

	{ int oargs[5], *oargp = oargs;
	if (lflag) {			/* Command-line options. */
		*oargp++ = O_LISP;
		*oargp++ = O_SHOWMATCH;
	}
	if (readonly)
		*oargp++ = O_READONLY;
	if (secure)
		*oargp++ = O_SECURE;
	*oargp = -1;			/* Options initialization. */
	if (opts_init(sp, oargs))
		goto err;
	}
	if (wsizearg != NULL) {
		ARGS *av[2], a, b;
		(void)snprintf(path, sizeof(path), "window=%s", wsizearg);
		a.bp = (CHAR_T *)path;
		a.len = strlen(path);
		b.bp = NULL;
		b.len = 0;
		av[0] = &a;
		av[1] = &b;
		(void)opts_set(sp, av, NULL);
	}
	if (silent) {			/* Ex batch mode option values. */
		O_CLR(sp, O_AUTOPRINT);
		O_CLR(sp, O_PROMPT);
		O_CLR(sp, O_VERBOSE);
		O_CLR(sp, O_WARN);
		F_SET(sp, SC_EX_SILENT);
	}

	sp->rows = O_VAL(sp, O_LINES);	/* Make ex formatting work. */
	sp->cols = O_VAL(sp, O_COLUMNS);

	if (!silent && startup) {	/* Read EXINIT, exrc files. */
		if (ex_exrc(sp))
			goto err;
		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
			if (screen_end(sp))
				goto err;
			goto done;
		}
	}

	/*
	 * List recovery files if -r specified without file arguments.
	 * Note, options must be initialized and startup information
	 * read before doing this.
	 */
	if (flagchk == 'r' && argv[0] == NULL) {
		if (rcv_list(sp))
			goto err;
		if (screen_end(sp))
			goto err;
		goto done;
	}

	/*
	 * !!!
	 * Initialize the default ^D, ^U scrolling value here, after the
	 * user has had every opportunity to set the window option.
	 *
	 * It's historic practice that changing the value of the window
	 * option did not alter the default scrolling value, only giving
	 * a count to ^D/^U did that.
	 */
	sp->defscroll = (O_VAL(sp, O_WINDOW) + 1) / 2;

	/*
	 * If we don't have a command-line option, switch into the right
	 * editor now, so that we position default files correctly, and
	 * so that any tags file file-already-locked messages are in the
	 * vi screen, not the ex screen.
	 *
	 * XXX
	 * If we have a command-line option, the error message can end
	 * up in the wrong place, but I think that the combination is
	 * unlikely.
	 */
	if (gp->c_option == NULL) {
		F_CLR(sp, SC_EX | SC_VI);
		F_SET(sp, LF_ISSET(SC_EX | SC_VI));
	}

	/* Open a tag file if specified. */
	if (tag_f != NULL) {
		CHAR2INT(sp, tag_f, strlen(tag_f) + 1, w, wlen);
		if (ex_tag_first(sp, w))
			goto err;
	}

	/*
	 * Append any remaining arguments as file names.  Files are recovery
	 * files if -r specified.  If the tag option or ex startup commands
	 * loaded a file, then any file arguments are going to come after it.
	 */
	if (*argv != NULL) {
		if (sp->frp != NULL) {
			/* Cheat -- we know we have an extra argv slot. */
			MALLOC_NOMSG(sp,
			    *--argv, char *, strlen(sp->frp->name) + 1);
			if (*argv == NULL) {
				v_estr(gp->progname, errno, NULL);
				goto err;
			}
			(void)strcpy(*argv, sp->frp->name);
		}
		sp->argv = sp->cargv = argv;
		F_SET(sp, SC_ARGNOFREE);
		if (flagchk == 'r')
			F_SET(sp, SC_ARGRECOVER);
	}
Ejemplo n.º 9
0
struct obj_conf *conf_init( int argc, char **argv ) {
	struct obj_conf *conf = (struct obj_conf *) myalloc( sizeof(struct obj_conf) );
	BEN *opts = opts_init();
	BEN *value = NULL;

	/* Parse command line */
	opts_load( opts, argc, argv );

	/* Mode */
	if( ben_searchDictStr( opts, "-d" ) != NULL ) {
		conf->mode = CONF_DAEMON;
	} else {
		conf->mode = CONF_CONSOLE;
	}

	/* Verbosity */
	if( ben_searchDictStr( opts, "-v" ) != NULL ) {
		conf->verbosity = CONF_VERBOSE;
	} else if ( ben_searchDictStr( opts, "-q" ) != NULL ) {
		conf->verbosity = CONF_BEQUIET;
	} else {
		/* Be verbose in the console and quiet while running as a daemon. */
		conf->verbosity = ( conf->mode == CONF_CONSOLE ) ?
			CONF_VERBOSE : CONF_BEQUIET;
	}

	/* Port */
	value = ben_searchDictStr( opts, "-p" );
	if( value != NULL && ben_str_size( value ) >= 1 ) {
		conf->port = atoi( (char *)value->v.s->s );
	} else {
		conf->port = CONF_PORT;
	}
	if( conf->port < CONF_PORTMIN || conf->port > CONF_PORTMAX ) {
		conf->port = CONF_PORT;
	}

	/* Cores */
	conf->cores = ( unix_cpus() > 2 ) ? unix_cpus() : CONF_CORES;
	if( conf->cores < 1 || conf->cores > 128 ) {
		fail( "Invalid number of CPU cores" );
	}

	/* HOME */
	conf_home( conf, opts );

#ifdef TUMBLEWEED
	/* HTML index */
	value = ben_searchDictStr( opts, "-i" );
	if( value != NULL && ben_str_size( value ) >= 1 ) {
		snprintf( conf->file, BUF_SIZE, "%s", (char *)value->v.s->s );
	} else {
		snprintf( conf->file, BUF_SIZE, "%s", CONF_INDEX_NAME );
	}
	if( !str_isValidFilename( conf->file ) ) {
		fail( "Index %s looks suspicious", conf->file );
	}
#endif

#ifdef TORRENTKINO
	/* Hostname */
	conf_hostname( conf, opts );

	/* Realm */
	value = ben_searchDictStr( opts, "-r" );
	if( value != NULL && ben_str_size( value ) >= 1 ) {
		snprintf( conf->realm, BUF_SIZE, "%s", (char *)value->v.s->s );
		conf->bool_realm = TRUE;
	} else {
		snprintf( conf->realm, BUF_SIZE, "%s", CONF_REALM );
		conf->bool_realm = FALSE;
	}

	/* Compute host_id. Respect the realm. */
	conf_hostid( conf->host_id, conf->hostname,
		conf->realm, conf->bool_realm );

	/* Announce this port */
	value = ben_searchDictStr( opts, "-b" );
	if( value != NULL && ben_str_size( value ) >= 1 ) {
		conf->announce_port = atoi( (char *)value->v.s->s );
	} else {
		conf->announce_port = CONF_ANNOUNCED_PORT;
	}
	if( conf->announce_port < CONF_PORTMIN || conf->announce_port > CONF_PORTMAX ) {
		fail( "Invalid announce port number. (-a)" );
	}

	if( getuid() == 0 ) {
		snprintf( conf->file, BUF_SIZE, "%s/%s", conf->home, CONF_FILE );
	} else {
		snprintf( conf->file, BUF_SIZE, "%s/.%s", conf->home, CONF_FILE );
	}

	/* Node ID */
	value = ben_searchDictStr( opts, "-n" );
	if( value != NULL && ben_str_size( value ) >= 1 ) {
		sha1_hash( conf->node_id, (char *)value->v.s->s, ben_str_size( value ) );
	} else {
		rand_urandom( conf->node_id, SHA1_SIZE );
	}

	memset( conf->null_id, '\0', SHA1_SIZE );

	/* Bootstrap node */
	value = ben_searchDictStr( opts, "-x" );
	if( value != NULL && ben_str_size( value ) >= 1 ) {
		snprintf( conf->bootstrap_node, BUF_SIZE, "%s", (char *)value->v.s->s );
	} else {
		snprintf( conf->bootstrap_node, BUF_SIZE, "%s", CONF_MULTICAST );
	}

	/* Bootstrap port */
	value = ben_searchDictStr( opts, "-y" );
	if( value != NULL && ben_str_size( value ) >= 1 ) {
		snprintf( conf->bootstrap_port, CONF_PORT_SIZE+1, "%s",
			value->v.s->s );
	} else {
		snprintf( conf->bootstrap_port, CONF_PORT_SIZE+1, "%i", CONF_PORT );
	}
	if( str_isSafePort( conf->bootstrap_port) < 0 ) {
		fail( "Invalid bootstrap port number. (-y)" );
	}

#ifdef POLARSSL
	/* Secret key */
	value = ben_searchDictStr( opts, "-k" );
	if( value != NULL && ben_str_size( value ) >= 1 ) {
		snprintf( conf->key, BUF_SIZE, "%s", (char *)value->v.s->s );
		conf->bool_encryption = TRUE;
	} else {
		memset( conf->key, '\0', BUF_SIZE );
		conf->bool_encryption = FALSE;
	}
#endif
#endif

	opts_free( opts );

	return conf;
}
Ejemplo n.º 10
0
/* main: application entry point.
 * @argc: the number of commandline arguments.
 * @argv: the commandline argument string array.
 */
int main (int argc, char **argv) {
  /* declare required variables. */
  pca_distance_metric metric;
  char *ifname, *metstr;
  struct matrix *D;
  struct pca *P;

  /* parse the command-line arguments. */
  if (!opts_init (argc, argv)) {
    /* output an error message and exit. */
    ferror ("failed to parse arguments");
    fprintf (stdout, HELP);
    return 1;
  }

  /* see if we should display the help message. */
  if (opts_geti (OPTS_S_HELP)) {
    /* print the help message and quit. */
    fprintf (stdout, HELP);
    return 0;
  }

  /* get the input filename. */
  ifname = opts_gets (OPTS_S_INPUT);

  /* ensure the input filename was provided. */
  if (!ifname) {
    /* output an error message and exit. */
    ferror ("input file required");
    fprintf (stdout, HELP);
    return 1;
  }

  /* read in the input file. */
  P = pca_new (ifname);

  /* make sure we read in the file. */
  if (!P) {
    /* output an error message and exit. */
    ferror ("failed to read '%s'", ifname);
    return 1;
  }

  /* set the default distance metric. */
  metric = pca_group_distance_euclidean;

  /* get the distance metric string. */
  metstr = opts_gets (OPTS_S_METRIC);

  /* see if the distance metric was provided. */
  if (metstr) {
    /* check the distance metric argument. */
    if (strncmp (metstr, "EUC", 3) == 0 ||
        strncmp (metstr, "euc", 3) == 0) {
      /* set the euclidean metric. */
      metric = pca_group_distance_euclidean;
    }
    else if (strncmp (metstr, "MAH", 3) == 0 ||
             strncmp (metstr, "mah", 3) == 0) {
      /* set the mahalanobis distance. */
      metric = pca_group_distance_mahalanobis;
    }
    else if (strncmp (metstr, "BHA", 3) == 0 ||
             strncmp (metstr, "bha", 3) == 0) {
      /* set the bhattacharyya distance. */
      metric = pca_group_distance_bhattacharyya;
    }
    else if (strncmp (metstr, "HEL", 3) == 0 ||
             strncmp (metstr, "hel", 3) == 0) {
      /* set the hellinger distance. */
      metric = pca_group_distance_hellinger;
    }
    else if (strncmp (metstr, "MIX", 3) == 0 ||
             strncmp (metstr, "mix", 3) == 0) {
      /* set the mixture distance. */
      metric = pca_group_distance_mixture;
    }
    else if (strncmp (metstr, "CHI", 3) == 0 ||
             strncmp (metstr, "chi", 3) == 0) {
      /* set the mixture distance. */
      metric = pca_group_distance_chisq;
    }
    else {
      /* output an error message and exit. */
      ferror ("unrecognized distance metric '%s'", metstr);
      fprintf (stdout, HELP);
      return 1;
    }
  }

  /* allocate a distance matrix. */
  D = matrix_new (P->n_groups, P->n_groups);

  /* make sure we allocated a matrix. */
  if (!D) {
    /* output an error message and exit. */
    ferror ("failed to allocate distance matrix");
    return 1;
  }

  /* calculate the distance matrix. */
  if (!pca_distances (P, D, metric)) {
    /* output an error message and exit. */
    ferror ("failed to calculate distance matrix");
    return 1;
  }

  /* write out the distance matrix. */
  pca_distances_print (P, D);

  /* free the distance matrix. */
  matrix_free (D);

  /* free the pca structure. */
  pca_free (P);

  /* return success. */
  return 0;
}
Ejemplo n.º 11
0
int
main(int argc, char *argv[])
{
    struct tcplay_opts *opts;
    int ch, error;
    int info_vol = 0, map_vol = 0,
        unmap_vol = 0, info_map = 0,
        create_vol = 0, modify_vol = 0;

    if ((error = tc_play_init()) != 0) {
        fprintf(stderr, "Initialization failed, exiting.");
        exit(EXIT_FAILURE);
    }

    atexit(check_and_purge_safe_mem);
    signal(SIGUSR1, sig_handler);
    signal(SIGINFO, sig_handler);

    if ((opts = opts_init()) == NULL) {
        fprintf(stderr, "Initialization failed (opts), exiting.");
        exit(EXIT_FAILURE);
    }

    opts->interactive = 1;

    while ((ch = getopt_long(argc, argv, "a:b:cd:ef:ghij:k:m:s:tu:vwx:y:zC:",
        longopts, NULL)) != -1) {
        switch(ch) {
        case 'a':
            if (opts->prf_algo != NULL)
                usage();
            if ((opts->prf_algo = check_prf_algo(optarg, 0)) == NULL) {
                if (strcmp(optarg, "help") == 0)
                    exit(EXIT_SUCCESS);
                else
                    usage();
                /* NOT REACHED */
            }
            break;
        case 'b':
            if (opts->cipher_chain != NULL)
                usage();
            if ((opts->cipher_chain = check_cipher_chain(optarg, 0)) == NULL) {
                if (strcmp(optarg, "help") == 0)
                    exit(EXIT_SUCCESS);
                else
                    usage();
                /* NOT REACHED */
            }
            break;
        case 'c':
            create_vol = 1;
            break;
        case 'C':
            opts->custom_iterations = atoi(optarg);
            break;
        case 'd':
            _set_str_opt(dev);
            break;
        case 'e':
            opts->protect_hidden = 1;
            break;
        case 'f':
            if ((error = opts_add_keyfile_hidden(opts, optarg)) != 0) {
                fprintf(stderr, "Could not add keyfile: %s\n", optarg);
                exit(EXIT_FAILURE);
            }
            break;
        case 'g':
            opts->hidden = 1;
            break;
        case 'i':
            info_vol = 1;
            break;
        case 'j':
            info_map = 1;
            _set_str_opt(map_name);
            break;
        case 'k':
            if ((error = opts_add_keyfile(opts, optarg)) != 0) {
                fprintf(stderr, "Could not add keyfile: %s\n", optarg);
                exit(EXIT_FAILURE);
            }
            break;
        case 'm':
            map_vol = 1;
            _set_str_opt(map_name);
            break;
        case 's':
            opts->flags |= TC_FLAG_SYS;
            _set_str_opt(sys_dev);
            break;
        case 't':
            opts->flags |= TC_FLAG_ALLOW_TRIM;
            break;
        case 'u':
            unmap_vol = 1;
            _set_str_opt(map_name);
            break;
        case 'v':
            printf("tcplay v%d.%d\n", MAJ_VER, MIN_VER);
            exit(EXIT_SUCCESS);
            /* NOT REACHED */
        case 'w':
            fprintf(stderr, "WARNING: Using urandom as source of "
                "entropy for key material is a really bad idea.\n");
            opts->weak_keys_and_salt = 1;
            break;
        case 'x':
            if (opts->h_prf_algo != NULL)
                usage();
            if ((opts->h_prf_algo = check_prf_algo(optarg, 0)) == NULL) {
                if (strcmp(optarg, "help") == 0)
                    exit(EXIT_SUCCESS);
                else
                    usage();
                /* NOT REACHED */
            }
            break;
        case 'y':
            if (opts->h_cipher_chain != NULL)
                usage();
            if ((opts->h_cipher_chain = check_cipher_chain(optarg, 0)) == NULL) {
                if (strcmp(optarg, "help") == 0)
                    exit(EXIT_SUCCESS);
                else
                    usage();
                /* NOT REACHED */
            }
            break;
        case 'z':
            opts->secure_erase = 0;
            break;
        case FLAG_LONG_FDE:
            opts->flags |= TC_FLAG_FDE;
            break;
        case FLAG_LONG_USE_BACKUP:
            opts->flags |= TC_FLAG_BACKUP;
            break;
        case FLAG_LONG_USE_HDR_FILE:
            opts->flags |= TC_FLAG_HDR_FROM_FILE;
            _set_str_opt(hdr_file_in);
            break;
        case FLAG_LONG_USE_HHDR_FILE:
            opts->flags |= TC_FLAG_H_HDR_FROM_FILE;
            _set_str_opt(h_hdr_file_in);
            break;
        case FLAG_LONG_MOD:
            modify_vol = 1;
            break;
        case FLAG_LONG_MOD_KF:
            if ((error = opts_add_keyfile_new(opts, optarg)) != 0) {
                fprintf(stderr, "Could not add keyfile: %s\n", optarg);
                exit(EXIT_FAILURE);
            }
            break;
        case FLAG_LONG_MOD_PRF:
            if (opts->new_prf_algo != NULL)
                usage();
            if ((opts->new_prf_algo = check_prf_algo(optarg, 0)) == NULL) {
                if (strcmp(optarg, "help") == 0)
                    exit(EXIT_SUCCESS);
                else
                    usage();
                /* NOT REACHED */
            }
            break;
        case FLAG_LONG_MOD_NONE:
            opts->new_prf_algo = NULL;
            opts->flags |= TC_FLAG_ONLY_RESTORE;
            opts->flags |= TC_FLAG_BACKUP;
            break;
        case FLAG_LONG_MOD_TO_FILE:
            opts->flags |= TC_FLAG_SAVE_TO_FILE;
            _set_str_opt(hdr_file_out);
            break;
        case FLAG_LONG_NO_RETRIES:
            opts->retries = 1;
            break;
        case 'h':
        case '?':
        default:
            usage();
            /* NOT REACHED */
        }
    }

    argc -= optind;
    argv += optind;

    /* Check arguments */
    if (!(((map_vol || info_vol || create_vol || modify_vol) && opts->dev != NULL) ||
        ((unmap_vol || info_map) && opts->map_name != NULL)) ||
        (TC_FLAG_SET(opts->flags, SYS) && TC_FLAG_SET(opts->flags, FDE)) ||
        (map_vol + info_vol + create_vol + unmap_vol + info_map + modify_vol > 1) ||
        (opts->hidden && !create_vol) ||
        (TC_FLAG_SET(opts->flags, SYS) && (opts->sys_dev == NULL)) ||
        (TC_FLAG_SET(opts->flags, ONLY_RESTORE) && (opts->n_newkeyfiles > 0 || opts->new_prf_algo != NULL)) ||
        (TC_FLAG_SET(opts->flags, BACKUP) && (opts->sys_dev != NULL || TC_FLAG_SET(opts->flags, FDE))) ||
        (map_vol && (opts->map_name == NULL)) ||
        (unmap_vol && (opts->map_name == NULL)) ||
        (!modify_vol && opts->n_newkeyfiles > 0) ||
        (!modify_vol && opts->new_prf_algo != NULL) ||
        (!modify_vol && TC_FLAG_SET(opts->flags, ONLY_RESTORE)) ||
        (!modify_vol && TC_FLAG_SET(opts->flags, SAVE_TO_FILE)) ||
        (!(opts->protect_hidden || create_vol) && opts->n_hkeyfiles > 0)) {
        usage();
        /* NOT REACHED */
    }

    /* Create a new volume */
    if (create_vol) {
        error = create_volume(opts);
        if (error) {
            tc_log(1, "could not create new volume on %s\n", opts->dev);
        }
    } else if (info_map) {
        error = info_mapped_volume(opts);
    } else if (info_vol) {
        error = info_volume(opts);
    } else if (map_vol) {
        error = map_volume(opts);
    } else if (unmap_vol) {
        error = dm_teardown(opts->map_name, NULL);
    } else if (modify_vol) {
        error = modify_volume(opts);
    }

    return error;
}
Ejemplo n.º 12
0
/* main: application entry point.
 * @argc: the number of commandline arguments.
 * @argv: the commandline argument string array.
 */
int main (int argc, char **argv) {
  /* declare required variables. */
  struct vector *x, *y, *z, *u;
  struct matrix *V, *R, *C;
  double theta;
  char *smean, *svar, *label;
  unsigned long n;
  int i;

  /* initialize the random number generator. */
  rand_init (time (NULL));

  /* parse the command-line arguments. */
  if (!opts_init (argc, argv)) {
    /* output an error message and exit. */
    ferror ("failed to parse arguments");
    fprintf (stdout, HELP);
    return 1;
  }

  /* see if we should display the help message. */
  if (opts_geti (OPTS_S_HELP)) {
    /* print the help message and quit. */
    fprintf (stdout, HELP);
    return 0;
  }

  /* get the number of points to produce. */
  n = opts_geti (OPTS_S_COUNT);

  /* ensure the point count is valid. */
  if (!n) {
    /* output an error message and exit. */
    ferror ("invalid point count (%lu)", n);
    fprintf (stdout, HELP);
    return 1;
  }

  /* get the points label. */
  label = opts_gets (OPTS_S_LABEL);

  /* ensure the points label is valid. */
  if (!label) {
    /* output an error message and exit. */
    ferror ("invalid label '%s'", label);
    fprintf (stdout, HELP);
    return 1;
  }

  /* allocate the math structures. */
  x = vector_new (2);
  y = vector_new (2);
  z = vector_new (2);
  u = vector_new (2);
  V = matrix_new (2, 2);
  R = matrix_new (2, 2);
  C = matrix_new (2, 2);

  /* ensure we allocated the math structures. */
  if (!x || !y || !z || !u || !V || !R || !C) {
    /* output an error message and exit. */
    ferror ("failed to allocate math structures");
    return 1;
  }

  /* get the mean string. */
  smean = opts_gets (OPTS_S_MEAN);

  /* did we get a mean string? */
  if (smean) {
    /* try to parse the string. */
    if (sscanf (smean, "(%lf,%lf)", &u->d[0], &u->d[1]) != 2) {
      /* output an error message and exit. */
      ferror ("failed to parse mean string '%s'", smean);
      fprintf (stdout, HELP);
      return 1;
    }
  }
  else {
    /* initialize to the origin. */
    u->d[0] = u->d[1] = 0.0;
  }

  /* get the variance string. */
  svar = opts_gets (OPTS_S_VAR);

  /* did we get a variance string? */
  if (svar) {
    /* try to parse the string. */
    if (sscanf (svar, "(%lf,%lf)", &V->d[0][0], &V->d[1][1]) != 2) {
      /* output an error message and exit. */
      ferror ("failed to parse variance string '%s'", svar);
      fprintf (stdout, HELP);
      return 1;
    }
  }
  else {
    /* initialize to unit variances. */
    V->d[0][0] = V->d[1][1] = 1.0;
  }

  /* get the rotation value. */
  theta = opts_getf (OPTS_S_ROT) / 180.0 * M_PI;

  /* build the rotation matrix. */
  R->d[0][0] = cos (theta);
  R->d[0][1] = -sin (theta);
  R->d[1][0] = sin (theta);
  R->d[1][1] = cos (theta);

  /* calculate the covariance matrix. */
  if (!matrix_matrix_mul (1.0, R, V, C)) {
    /* output an error message and exit. */
    ferror ("failed to calculate covariance matrix");
    return 1;
  }

  /* see if we should produce a header. */
  if (opts_geti (OPTS_S_HEADER)) {
    /* yep. print one. */
    fprintf (stdout,
      "Obs ID (Primary)\tObs ID (Obs. Sec. ID:1)\tM1.t[2]\tM1.t[1]\n");
  }

  /* loop a set number of times. */
  for (i = 0; i < n; i++) {
    /* calculate the two values. */
    x->d[0] = randnormal ();
    x->d[1] = randnormal ();

    /* scale the values. */
    if (!matrix_vector_mul (1.0, C, x, y)) {
      /* output an error message and exit. */
      ferror ("failed to scale random variate %d", i + 1);
      return 1;
    }

    /* translate the values. */
    if (!vector_sum (1.0, y, 1.0, u, z)) {
      /* output an error message and exit. */
      ferror ("failed to translate random variate %d", i + 1);
      return 1;
    }

    /* print the values. */
    fprintf (stdout, "%d\t%s\t%lf\t%lf\n", i + 1, label, z->d[0], z->d[1]);
  }

  /* free the math structures. */
  vector_free (x);
  vector_free (y);
  vector_free (z);
  vector_free (u);
  matrix_free (V);
  matrix_free (R);
  matrix_free (C);

  /* return success. */
  return 0;
}
Ejemplo n.º 13
0
/*--------------------------------------------------------- */
int main(int argc, char **argv)
{
	int retval = -1;
	struct options *opts = NULL;
	int pidfd = -1;
	unsigned int interval;

	/* Signal vars */
	struct sigaction sig_act;
	sigset_t sig_set;

	/* IRQ list. It contain all found IRQs. */
	lub_list_t *irqs;
	/* IRQs need to be balanced */
	lub_list_t *balance_irqs;
	/* CPU list. It contain all found CPUs. */
	lub_list_t *cpus;
	/* NUMA list. It contain all found NUMA nodes. */
	lub_list_t *numas;
	/* Proximity list. */
	lub_list_t *pxms;

	/* Parse command line options */
	opts = opts_init();
	if (opts_parse(argc, argv, opts))
		goto err;

	/* Initialize syslog */
	openlog(argv[0], LOG_CONS, opts->log_facility);
	syslog(LOG_ERR, "Start daemon.\n");

	/* Fork the daemon */
	if (!opts->debug) {
		/* Daemonize */
		if (daemon(0, 0) < 0) {
			syslog(LOG_ERR, "Can't daemonize\n");
			goto err;
		}

		/* Write pidfile */
		if ((pidfd = open(opts->pidfile,
			O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
			S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
			syslog(LOG_WARNING, "Can't open pidfile %s: %s",
				opts->pidfile, strerror(errno));
		} else {
			char str[20];
			snprintf(str, sizeof(str), "%u\n", getpid());
			str[sizeof(str) - 1] = '\0';
			if (write(pidfd, str, strlen(str)) < 0)
				syslog(LOG_WARNING, "Can't write to %s: %s",
					opts->pidfile, strerror(errno));
			close(pidfd);
		}
	}

	/* Set signal handler */
	sigemptyset(&sig_set);
	sigaddset(&sig_set, SIGTERM);
	sigaddset(&sig_set, SIGINT);
	sigaddset(&sig_set, SIGQUIT);

	sig_act.sa_flags = 0;
	sig_act.sa_mask = sig_set;
	sig_act.sa_handler = &sighandler;
	sigaction(SIGTERM, &sig_act, NULL);
	sigaction(SIGINT, &sig_act, NULL);
	sigaction(SIGQUIT, &sig_act, NULL);

	/* Randomize */
	srand(time(NULL));

	/* Scan NUMA nodes */
	numas = lub_list_new(numa_list_compare);
	scan_numas(numas);
	if (opts->verbose)
		show_numas(numas);

	/* Scan CPUs */
	cpus = lub_list_new(cpu_list_compare);
	scan_cpus(cpus, opts->ht);
	if (opts->verbose)
		show_cpus(cpus);

	/* Prepare data structures */
	irqs = lub_list_new(irq_list_compare);
	balance_irqs = lub_list_new(irq_list_compare);

	/* Parse proximity file */
	pxms = lub_list_new(NULL);
	if (opts->pxm)
		parse_pxm_config(opts->pxm, pxms, numas);
	if (opts->verbose)
		show_pxms(pxms);

	/* Main loop */
	while (!sigterm) {
		lub_list_node_t *node;
		char outstr[10];
		time_t t;
		struct tm *tmp;

		t = time(NULL);
		tmp = localtime(&t);
		if (tmp) {
			strftime(outstr, sizeof(outstr), "%H:%M:%S", tmp);
			printf("----[ %s ]----------------------------------------------------------------\n", outstr);
		}

		/* Rescan PCI devices for new IRQs. */
		scan_irqs(irqs, balance_irqs, pxms);
		if (opts->verbose)
			irq_list_show(irqs);
		/* Link IRQs to CPUs due to real current smp affinity. */
		link_irqs_to_cpus(cpus, irqs);

		/* Gather statistics on CPU load and number of interrupts. */
		gather_statistics(cpus, irqs);
		show_statistics(cpus, opts->verbose);
		/* Choose IRQ to move to another CPU. */
		choose_irqs_to_move(cpus, balance_irqs,
			opts->threshold, opts->strategy);

		/* If nothing to balance */
		if (lub_list_len(balance_irqs) != 0) {
			/* Set short interval to make balancing faster. */
			interval = opts->short_interval;
			/* Choose new CPU for IRQs need to be balanced. */
			balance(cpus, balance_irqs, opts->threshold);
			/* Write new values to /proc/irq/<IRQ>/smp_affinity */
			apply_affinity(balance_irqs);
			/* Free list of balanced IRQs */
			while ((node = lub_list__get_tail(balance_irqs))) {
				lub_list_del(balance_irqs, node);
				lub_list_node_free(node);
			}
		} else {
			/* If nothing to balance */
			interval = opts->long_interval;
		}
		
		/* Wait before next iteration */
		sleep(interval);
	}

	/* Free data structures */
	irq_list_free(irqs);
	lub_list_free(balance_irqs);
	cpu_list_free(cpus);
	numa_list_free(numas);
	pxm_list_free(pxms);

	retval = 0;
err:
	/* Remove pidfile */
	if (pidfd >= 0) {
		if (unlink(opts->pidfile) < 0) {
			syslog(LOG_ERR, "Can't remove pid-file %s: %s\n",
			opts->pidfile, strerror(errno));
		}
	}

	/* Free command line options */
	opts_free(opts);
	syslog(LOG_ERR, "Stop daemon.\n");

	return retval;
}
Ejemplo n.º 14
0
/* main: application entry point.
 * @argc: the number of commandline arguments.
 * @argv: the commandline argument string array.
 */
int main (int argc, char **argv) {
    /* declare required variables. */
    unsigned long g, i, j;
    struct pca *P;
    char *ifname;

    /* parse the command-line arguments. */
    if (!opts_init (argc, argv)) {
        /* output an error message and exit. */
        ferror ("failed to parse arguments");
        fprintf (stdout, HELP);
        return 1;
    }

    /* see if we should display the help message. */
    if (opts_geti (OPTS_S_HELP)) {
        /* print the help message and quit. */
        fprintf (stdout, HELP);
        return 0;
    }

    /* get the input filename. */
    ifname = opts_gets (OPTS_S_INPUT);

    /* ensure the input filename was provided. */
    if (!ifname) {
        /* output an error message and exit. */
        ferror ("input file required");
        fprintf (stdout, HELP);
        return 1;
    }

    /* read the input file. */
    P = pca_new (ifname);

    /* make sure we read in the file. */
    if (!P) {
        /* output an error message and exit. */
        ferror ("failed to read '%s'", ifname);
        return 1;
    }

    /* calculate the map. */
    if (!pca_calculate_maps (P)) {
        /* output an error message and exit. */
        ferror ("failed to calculate density maps");
        return 1;
    }

    /* loop through the groups. */
    for (g = 0; g < P->n_groups; g++) {
        /* loop through the map rows. */
        for (i = 0; i < P->groups[g]->map->m; i++) {
            /* loop through the map columns. */
            for (j = 0; j < P->groups[g]->map->n; j++) {
                /* output the value. */
                fprintf (stdout, "%lu %le %le %le\n", g,
                         P->groups[g]->mx->d[i],
                         P->groups[g]->my->d[j],
                         P->groups[g]->map->d[i][j]);
            }
        }
    }

    /* free the pca structure. */
    pca_free (P);

    /* return success. */
    return 0;
}