Example #1
0
int main(int argc, char *argv[])
{
    /* basename $0 */
    package = strrchr(argv[0], '/');
    if (package == 0)
        package = argv[0];
    else
        package++;

    /* become a new client of the JACK server */
    synchro = new TJackSynchro();
    synchro->Open();
	
    //synchro->AddMidiBus(1);
    //synchro->AddMidiBus(2);

    signal(SIGQUIT, signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGHUP, signal_handler);
    signal(SIGINT, signal_handler);

    /* execute commands until done */
    command_loop();

    synchro->Close();
    delete synchro;
    exit(0);
}
Example #2
0
int cmd_remote_ext(int argc, const char **argv, const char *prefix)
{
	if (argc != 3)
		die("Expected two arguments");

	return command_loop(argv[2]);
}
Example #3
0
void console_start(void)
{
	debug_buffer = malloc(LINE_LEN);

	dprintf(INFO, "entering main console loop\n");

	for (;;)
		command_loop(&read_debug_line, NULL, true, false);
}
Example #4
0
int
main(
	int	argc,
	char	**argv)
{
	init(argc, argv);
	command_loop();
	return exitcode;
}
int main(int argc, char** argv) {

	if (argc != 3 && argc != 4) {
		fprintf(stderr, "%s\n", usage); 
		exit(EXIT_FAILURE); 
	}	

	basic_input = false; 

	if (argc == 4 && strcmp(argv[3], "--stdin") == 0) {
		basic_input = true; 
	}
	else if (argc == 4) { //Gave invalid final argument
		fprintf(stderr, "Invalid arg: '%s'\n%s", argv[3], usage); 
		exit(EXIT_FAILURE); 
	}

	int server_socket = -1; 
	int error = -1; 
	char* host = argv[1];
	char* port = argv[2]; 

	init_curses(basic_input); //Init window for ncurses interface
	draw_msgs(); //Draw empty chat window

	server_socket = connect_to_server(host, port); 

	if (server_socket < 0) {
		endwin(); 
		printf("Error connecting to server %s on socket %s\n", host, port); 
		exit(EXIT_FAILURE); 
	}

	if ((LOG_FD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, S_IRWXU)) < 0) {
		printf("Error opening log file: %s\n", strerror(errno)); 
	}	

	error = pthread_create(&(receive_thread), NULL, (void*(*)(void*)) receive_loop, (void*) &server_socket); 

	if (error != 0) {
		endwin(); 
		pthread_cancel(receive_thread); 
		printf("Error creating pthread. Exiting program.\n"); 
		exit(EXIT_FAILURE); 
	}	

	command_loop(server_socket); 

	pthread_cancel(receive_thread); 

	endwin(); //Shouldn't ever reach this code. But, close window if this happens. 

	return 0;
}
Example #6
0
File: main.c Project: dholm/kernel
void kmain(const multiboot_info_t* multi_boot_info, unsigned int multiboot_magic)
{
    if (MULTIBOOT_BOOTLOADER_MAGIC != multiboot_magic) {
        return;
    }
    (void) multi_boot_info;

    serial_init();
    printf("Welcome to the future!\n");
    command_init();
    command_loop();
}
Example #7
0
int main(void) {
	init();
	
//	sd_open();
//	gpio_led_test();
//	gpio_input_test();
//	fatfs_test("test.txt");
//	while (1) {
//		tickTack();
//		delay_ms(1000);
//	}
	command_loop();
}
Example #8
0
/*=========================================================================================================
	MAIN
=========================================================================================================*/
int main(int argc, char* argv[]) 
{
	m_filename = get_filename(argv[1]);
	open_file(m_filename, "r+");
	load_MusicLibrary();
	char ch;
	do
	{
		ch = command_loop();
	} while (ch != 'q');

	return 0;
}
Example #9
0
static int console_run_script_etc(const char *string, bool locked)
{
	struct line_read_struct lineread;

	lineread.string = string;
	lineread.pos = 0;
	lineread.buffer = malloc(LINE_LEN);
	lineread.buflen = LINE_LEN;

	command_loop(&fetch_next_line, (void *)&lineread, false, locked);

	return lastresult;
}
Example #10
0
void console_start(void)
{
    debug_buffer = malloc(LINE_LEN);

    dprintf(INFO, "entering main console loop\n");


    while (command_loop(&read_debug_line, NULL, true, false) == NO_ERROR)
        ;

    dprintf(INFO, "exiting main console loop\n");

    free (debug_buffer);
}
Example #11
0
int
main(int argc, char **argv)
{
	const char *av = NULL;
	int optchar;
	int option_index = 0;

	while ((optchar = getopt_long(argc, argv, "bCcdeF:f:hI:i:kLlp:qRs:TUuVv0123456789", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			break;
		case 'C':
			ignore_case = 1;
			break;
		case 'q':
			qflag++;
			break;
		case 'v':
			vflag++;
			break;
		default:
			break;
		}
	}
	if (show_help)
		help();
	argc -= optind;
	argv += optind;
	if (!av)
		av = (argc > 0) ? *argv : NULL;
	if (show_version)
		version(av, vflag);
	/*
	 * Get global(1)'s path. If not found, abort with a message.
	 */
	get_global_path();
	/*
	 * Check dbpath. If dbpath not found, abort with a message.
	 */
	check_dbpath();
	/*
	 * Command loop
	 */
	command_loop();
	return 0;
}
Example #12
0
/** 
 * <JA>
 * メイン
 * 
 * @param argc [in] 引数の数
 * @param argv [in] 引数列
 * 
 * @return 正常終了時 0, エラー終了時 1 を返す.
 * </JA>
 * <EN>
 * Main function.
 * 
 * @param argc [in] number of arguments
 * @param argv [in] argument array
 * 
 * @return 0 on normal exit, 1 on error exit.
 * </EN>
 */
int
main(int argc, char *argv[])
{
  int port;
  int sd;
  
  if (argc < 2) {
    usage();
    return 1;
  }
  if (argc < 3) {
    port = DEFAULT_PORT;
  } else {
    port = atoi(argv[2]);
  }
  sd = do_connect(argv[1], port);
  command_loop(sd);

  return 0;
}
Example #13
0
File: simple.c Project: estock/spot
int main(int argc, char** argv)
{
    setlocale(LC_ALL, "");

    if (argc < 3) {
        wprintf(L"Usage: %s <username> <password>\n", argv[0]);
        return 1;
    }

    if (!despotify_init())
    {
        wprintf(L"despotify_init() failed\n");
        return 1;
    }

    struct despotify_session* ds = despotify_init_client(callback);
    if (!ds) {
        wprintf(L"despotify_init_client() failed\n");
        return 1;
    }

    if (!despotify_authenticate(ds, argv[1], argv[2])) {
        printf( "Authentication failed: %s\n", despotify_get_error(ds));
        despotify_exit(ds);
        return 1;
    }

    print_info(ds);

    command_loop(ds);

    despotify_exit(ds);

    if (!despotify_cleanup())
    {
        wprintf(L"despotify_cleanup() failed\n");
        return 1;
    }

    return 0;
}
Example #14
0
static int
captured_command_loop (void *data)
{
  if (command_loop_hook == NULL)
    command_loop ();
  else
    command_loop_hook ();
  /* FIXME: cagney/1999-11-05: A correct command_loop() implementaton
     would clean things up (restoring the cleanup chain) to the state
     they were just prior to the call.  Technically, this means that
     the do_cleanups() below is redundant.  Unfortunately, many FUNCs
     are not that well behaved.  do_cleanups should either be replaced
     with a do_cleanups call (to cover the problem) or an assertion
     check to detect bad FUNCs code. */
  do_cleanups (ALL_CLEANUPS);
  /* If the command_loop returned, normally (rather than threw an
     error) we try to quit. If the quit is aborted, catch_errors()
     which called this catch the signal and restart the command
     loop. */
  quit_command (NULL, instream == stdin);
  return 1;
}
Example #15
0
int main(int argc, char *argv[])
{
	jack_status_t status;

	/* basename $0 */
	package = strrchr(argv[0], '/');
	if (package == 0)
		package = argv[0];
	else
		package++;

	/* open a connection to the JACK server */
	client = jack_client_open (package, JackNullOption, &status);
	if (client == NULL) {
		fprintf (stderr, "jack_client_open() failed, "
			 "status = 0x%2.0x\n", status);
		return 1;
	}

#if !WIN32
	signal(SIGQUIT, signal_handler);
	signal(SIGHUP, signal_handler);
#endif
	signal(SIGTERM, signal_handler);
	signal(SIGINT, signal_handler);

	jack_on_shutdown(client, jack_shutdown, 0);

	if (jack_activate(client)) {
		fprintf(stderr, "cannot activate client");
		return 1;
	}

	/* execute commands until done */
	command_loop();

	jack_client_close(client);
	exit(0);
}
Example #16
0
/* -------------------initiate ftp server-------------------
*/
int run_ftp(int port)
{

	memset(&listen_conn, 0, sizeof(connection));

	listen_conn.saddr.sin_port = htons(port);

	if (create_listen_socket(&listen_conn) < 0) {
		printlog("%s","create_listen_socket FAILED\n");
		exit(1);
	}

	for (;;) {
		if (accept_connection( &listen_conn, &sconn) < 0) {
			printlog("%s","accept_connection FAILED\n");
			continue;
		}

		signal(SIGCHLD, SIG_IGN);

		if (fork() == 0) {
        		close_conn(listen_conn);

        		status = CONNECTED;

        		send_greetings();

        		command_loop();

        		close_conn(sconn);
        		return 0;
		}

        	close_conn(sconn);
	}

	return 0;
}
Example #17
0
int main (int argc, const char *argv[])
{

    // Check input
    if (argc < 2) {
        printf("Usage: passmate-cli <path_to_storage>\n");
        abort();
    }

    // Get and check storage path
    char * storage_path = argv[1];
    if (fopen(storage_path, "rb") == NULL) {
        printf("Path to a storage file is wrong.\n");
        abort();
    }

    // Save storage path
    __db_path__ = (char *) malloc(sizeof(char) * (strlen(storage_path) + 1));
    strcpy(__db_path__, storage_path);

    // Get and check master key
    char * key = getpass("Enter your master key: ");
    if (strlen(key) < 5) {
        printf("Your master key is too short. It has to be longer than 5 characters.\n");
        abort();
    }

    // Get and check storage
    __storage__ = storage_read_from_file(storage_path, key);
    if (__storage__ == NULL) __storage__ = storage_init(key);

    // Run loop
    printf("Passmate CLI %s\n", PASSMATE_CLI_VERSION);
    printf("Type 'help' for more information\n");
    command_loop();

    return 0;
}
int main(int argc, char **argv){
    register_segfault_handler();
    command_loop();

    return 0;
}
Example #19
0
int main(int argc, char **argv)
{
    int readonly = 0;
    int growable = 0;
    const char *sopt = "hVc:d:rsnmgkt:T:";
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "offset", 1, NULL, 'o' },
        { "cmd", 1, NULL, 'c' },
        { "read-only", 0, NULL, 'r' },
        { "snapshot", 0, NULL, 's' },
        { "nocache", 0, NULL, 'n' },
        { "misalign", 0, NULL, 'm' },
        { "growable", 0, NULL, 'g' },
        { "native-aio", 0, NULL, 'k' },
        { "discard", 1, NULL, 'd' },
        { "cache", 1, NULL, 't' },
        { "trace", 1, NULL, 'T' },
        { NULL, 0, NULL, 0 }
    };
    int c;
    int opt_index = 0;
    int flags = BDRV_O_UNMAP;

#ifdef CONFIG_POSIX
    signal(SIGPIPE, SIG_IGN);
#endif

    progname = basename(argv[0]);

    while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
        switch (c) {
        case 's':
            flags |= BDRV_O_SNAPSHOT;
            break;
        case 'n':
            flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
            break;
        case 'd':
            if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
                error_report("Invalid discard option: %s", optarg);
                exit(1);
            }
            break;
        case 'c':
            add_user_command(optarg);
            break;
        case 'r':
            readonly = 1;
            break;
        case 'm':
            qemuio_misalign = 1;
            break;
        case 'g':
            growable = 1;
            break;
        case 'k':
            flags |= BDRV_O_NATIVE_AIO;
            break;
        case 't':
            if (bdrv_parse_cache_flags(optarg, &flags) < 0) {
                error_report("Invalid cache option: %s", optarg);
                exit(1);
            }
            break;
        case 'T':
            if (!trace_backend_init(optarg, NULL)) {
                exit(1); /* error message will have been printed */
            }
            break;
        case 'V':
            printf("%s version %s\n", progname, QEMU_VERSION);
            exit(0);
        case 'h':
            usage(progname);
            exit(0);
        default:
            usage(progname);
            exit(1);
        }
    }

    if ((argc - optind) > 1) {
        usage(progname);
        exit(1);
    }

    qemu_init_main_loop();
    bdrv_init();

    /* initialize commands */
    qemuio_add_command(&quit_cmd);
    qemuio_add_command(&open_cmd);
    qemuio_add_command(&close_cmd);

    if (isatty(STDIN_FILENO)) {
        readline_state = readline_init(readline_printf_func,
                                       readline_flush_func,
                                       NULL,
                                       readline_completion_func);
        qemu_set_tty_echo(STDIN_FILENO, false);
        atexit(reenable_tty_echo);
    }

    /* open the device */
    if (!readonly) {
        flags |= BDRV_O_RDWR;
    }

    if ((argc - optind) == 1) {
        openfile(argv[optind], flags, growable, NULL);
    }
    command_loop();

    /*
     * Make sure all outstanding requests complete before the program exits.
     */
    bdrv_drain_all();

    if (qemuio_bs) {
        bdrv_unref(qemuio_bs);
    }
    g_free(readline_state);
    return 0;
}
Example #20
0
/************************************************************************
 *      main() Initialize & start citadel
 ************************************************************************/
void main(int argc, char *argv[])
{
    int i, cfg_ctdl = FALSE;
    long b;
    char init_baud;
    static char prompt[92];
    char *envprompt;

    cfg.bios = 1;
	cit_init_timer();			/* initialize cit_time() and cit_timer()	*/
    cfg.attr = 7;       		/* logo gets white letters                  */
    setscreen();				/* initialize screen system					*/
	memset(&parm,0,sizeof(parm));
    for (i = 1; i < argc; i++) {
        if (argv[i][0] == '/'
        || argv[i][0] == '-') {
            switch (tolower(argv[i][1])) {
#ifndef ATARI_ST
                case 'd':       /* DesqView/TopView     */
                    parm.dv = 1;
                    cPrintf("DesqView/TopView mode\n");
                    break;

                case 'b':       /* baud rate (for shell) */
                    if (argv[i + 1]) {
						b = atol(argv[++i]);
                        for (init_baud = 0; bauds[init_baud]; ++init_baud)
                            if (bauds[init_baud] == b) {
                                parm.baud = init_baud;
                                cPrintf("Initial baud rate fixed at %ld\n", b);
                                break;
							}
                    }
                    break;
				case 'm':
					parm.memcheck = !parm.memcheck;
					break;
#endif
                case 'c':       /* Configure system     */
                    cfg_ctdl = TRUE;
                    break;

                case 'p':       /* pace output          */
                    if (argv[i + 1]) {
                        parm.pace = atoi(argv[++i]);
                        cPrintf("Output pacing %d\n", parm.pace);
                    }
                    break;

                case 's':       /* run in shell from another BBS (door).        */
                    cPrintf("Shell mode\n");
                    parm.door = TRUE;
                    break;
/*#ifndef ATARI_ST*/
#ifndef FLOPPY
                case 'e':       /* use EMS                      */
                    if (_OvrInitEms(0, 0, 0)) {
                        cPrintf("EMS memory initialization failed!\n");
                        parm.ems = 1;
                    }
                    break;
#endif
/*#endif*/
				case 'v':       /* just do events       */
                    parm.events = 1;
                    break;
/*#ifndef ATARI_ST*/
#ifndef FLOPPY
                case 'x':       /* use exteneded memory */
					if (_OvrInitExt(0, 0))
                        cPrintf("Extended memory initialization failed!\n");
                    parm.ext = 1;
                    break;
#endif
/*#endif*/
				case 'l':		/* log in user */
                    if (argv[i + 1]) {
						parm.login = argv[++i];
						cPrintf("Auto-login\n");
					}
					break;

				case 'u':		/* log in user */
                    if (argv[i + 1]) {
						parm.user = argv[++i];
						cPrintf("Auto-login %s\n", parm.user);
					}
					break;
					
                default:
                    cPrintf("\nUnknown commandline switch '%s'.\n", argv[i]);
                    cPrintf("Valid DOS command line switches:\n");
                    cPrintf("    -b baud   Starting baud rate (300-19200)\n");
                    cPrintf("    -c        Read configuration files\n");
                    cPrintf("    -d        DesqView/TopView\n");
#ifndef FLOPPY
                    cPrintf("    -e        Use EMS memory for overlays\n");
#endif
					cPrintf("    -l str    Log in using initials;password in str\n");
					cPrintf("    -m        Memory check during idle time, start\n");
                    cPrintf("    -p num    Set output pacing to num\n");
                    cPrintf("    -s        Run as a shell from another BBS\n");
					cPrintf("    -u 'name' Log in using specifed user name");
                    cPrintf("    -v        Just run cron events\n");
#ifndef FLOPPY
					cPrintf("    -x        Use extended memory for overlays (386/486 only!)\n");
#endif
                    exit(1);
            }
        }
    }

    if (cfg_ctdl)				/* force reconfigure?						*/
        unlink("etc.tab");

    logo();						/* prints out system logo                   */

    if (cit_time() < 607415813L) {
        cPrintf("\n\nPlease set your time and date!\n");
        exit(1);
    }
	/* set prompt for shells */
    envprompt = getenv("PROMPT");
	if (!envprompt)
		envprompt = "$p$g";
    sprintf(prompt, "PROMPT=\r\nType EXIT to return to FredCit\r\n%s", envprompt);
    if (putenv(prompt)) {
        cPrintf("\n\nCan not set DOS prompt!\n");
		delay (5000);
	}
	/* initialize citadel */
    initCitadel();

    if (parm.baud) {
        cfg.initbaud = parm.baud;
        baud(cfg.initbaud);
    }
	if (parm.door) {
		detectflag = 1;
//		carrier();
//		if (haveCarrier) {
//			carrdetect();
//			newCarrier = 1;		/* make hello blurb show up */
//		}
	}
    greeting();

	sysReq = FALSE;

	if (cfg.f6pass[0])
		ConLock = TRUE;

	if (parm.dv) {
		cfg.bios = 1;
		directvideo = 0;
	}

	if (parm.login) {
		normalizeString(parm.login);	/* normalize string in environment */
		login(parm.login,NULL);
	} else if (parm.user && !loggedIn) {
		normalizeString(parm.user);	/* normalize string in environment */
		if (findPerson(parm.user, &lBuf) != ERROR)
			login(lBuf.lbin,lBuf.lbpw);
	}

		/* read in door interface files */
	if (parm.door) {
		readDoorFiles(0);
	}
	/* update25();	*/
	do_idle(0);

	/* install critical error handler */
	harderr(cit_herror_handler);
	
	/* execute main command loop */
    if (!parm.events)
        command_loop();
    else {
        do_cron_loop();
    }

    exitcitadel();
}
Example #21
0
int main(int argc, char** argv)
{
    setlocale(LC_ALL, "");

    if (argc < 3) {
        wrapper_wprintf(L"Usage: %s <username> <password> [remote control port]\n", argv[0]);
        return 1;
    }

    DSFYDEBUG("$Id$\n");
    if (!despotify_init())
    {
        wrapper_wprintf(L"despotify_init() failed\n");
        return 1;
    }

    struct despotify_session* ds = despotify_init_client(callback, NULL, true, true);
    if (!ds) {
        wrapper_wprintf(L"despotify_init_client() failed\n");
        return 1;
    }

    pthread_create(&thread, NULL, &thread_loop, ds);

    if(argc == 4 && wrapper_listen(atoi(argv[3]))) {
        wrapper_wprintf(L"wrapper_listen() failed to listen on local port %s\n", argv[3]);
    	return 1;
    }

    if (!despotify_authenticate(ds, argv[1], argv[2])) {
        printf( "Authentication failed: %s\n", despotify_get_error(ds));
        despotify_exit(ds);
        return 1;
    }

    audio_device = audio_init();

#if 0
    {
        struct ds_track* t = despotify_get_track(ds, "d1b264bb6bcd46be852ceba8ac5e6582");
        despotify_play(ds, t, false);
        thread_play();

        while(1) {
            sleep(1);
        }
    }
#else
    print_info(ds);

    command_loop(ds);
#endif
    thread_exit();
    audio_exit(audio_device);
    despotify_exit(ds);
    
    if (!despotify_cleanup())
    {
        wrapper_wprintf(L"despotify_cleanup() failed\n");
        return 1;
    }

    return 0;
}
Example #22
0
File: command.cpp Project: att/uwin
void process_commands(const char *file)
{
  input_stack::init();
  input_stack::push_file(file);
  command_loop();
}
Example #23
0
static int
captured_main (void *data)
{
  struct captured_main_args *context = data;
  int argc = context->argc;
  char **argv = context->argv;
  int count;
  static int quiet = 0;
  static int batch = 0;
  static int set_args = 0;

  /* Pointers to various arguments from command line.  */
  char *symarg = NULL;
  char *execarg = NULL;
  char *corearg = NULL;
  char *cdarg = NULL;
  char *ttyarg = NULL;

  /* These are static so that we can take their address in an initializer.  */
  static int print_help;
  static int print_version;

  /* Pointers to all arguments of --command option.  */
  char **cmdarg;
  /* Allocated size of cmdarg.  */
  int cmdsize;
  /* Number of elements of cmdarg used.  */
  int ncmd;

  /* Indices of all arguments of --directory option.  */
  char **dirarg;
  /* Allocated size.  */
  int dirsize;
  /* Number of elements used.  */
  int ndir;

  struct stat homebuf, cwdbuf;
  char *homedir, *homeinit;

  register int i;

  long time_at_startup = get_run_time ();

#if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
  setlocale (LC_MESSAGES, "");
#endif
#if defined (HAVE_SETLOCALE)
  setlocale (LC_CTYPE, "");
#endif
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  START_PROGRESS (argv[0], 0);

#ifdef MPW
  /* Do all Mac-specific setup. */
  mac_init ();
#endif /* MPW */

  /* This needs to happen before the first use of malloc.  */
  init_malloc ((PTR) NULL);

#if defined (ALIGN_STACK_ON_STARTUP)
  i = (int) &count & 0x3;
  if (i != 0)
    alloca (4 - i);
#endif

  cmdsize = 1;
  cmdarg = (char **) xmalloc (cmdsize * sizeof (*cmdarg));
  ncmd = 0;
  dirsize = 1;
  dirarg = (char **) xmalloc (dirsize * sizeof (*dirarg));
  ndir = 0;

  quit_flag = 0;
  line = (char *) xmalloc (linesize);
  line[0] = '\0';		/* Terminate saved (now empty) cmd line */
  instream = stdin;

  getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
  current_directory = gdb_dirbuf;

  gdb_stdout = stdio_fileopen (stdout);
  gdb_stderr = stdio_fileopen (stderr);
  gdb_stdlog = gdb_stderr;	/* for moment */
  gdb_stdtarg = gdb_stderr;	/* for moment */

  /* initialize error() */
  error_init ();

  /* Parse arguments and options.  */
  {
    int c;
    /* When var field is 0, use flag field to record the equivalent
       short option (or arbitrary numbers starting at 10 for those
       with no equivalent).  */
    static struct option long_options[] =
    {
      {"async", no_argument, &event_loop_p, 1},
      {"noasync", no_argument, &event_loop_p, 0},
#if defined(TUI)
      {"tui", no_argument, &tui_version, 1},
#endif
      {"xdb", no_argument, &xdb_commands, 1},
      {"dbx", no_argument, &dbx_commands, 1},
      {"readnow", no_argument, &readnow_symbol_files, 1},
      {"r", no_argument, &readnow_symbol_files, 1},
      {"mapped", no_argument, &mapped_symbol_files, 1},
      {"m", no_argument, &mapped_symbol_files, 1},
      {"quiet", no_argument, &quiet, 1},
      {"q", no_argument, &quiet, 1},
      {"silent", no_argument, &quiet, 1},
      {"nx", no_argument, &inhibit_gdbinit, 1},
      {"n", no_argument, &inhibit_gdbinit, 1},
      {"batch", no_argument, &batch, 1},
      {"epoch", no_argument, &epoch_interface, 1},

    /* This is a synonym for "--annotate=1".  --annotate is now preferred,
       but keep this here for a long time because people will be running
       emacses which use --fullname.  */
      {"fullname", no_argument, 0, 'f'},
      {"f", no_argument, 0, 'f'},

      {"annotate", required_argument, 0, 12},
      {"help", no_argument, &print_help, 1},
      {"se", required_argument, 0, 10},
      {"symbols", required_argument, 0, 's'},
      {"s", required_argument, 0, 's'},
      {"exec", required_argument, 0, 'e'},
      {"e", required_argument, 0, 'e'},
      {"core", required_argument, 0, 'c'},
      {"c", required_argument, 0, 'c'},
      {"pid", required_argument, 0, 'p'},
      {"p", required_argument, 0, 'p'},
      {"command", required_argument, 0, 'x'},
      {"version", no_argument, &print_version, 1},
      {"x", required_argument, 0, 'x'},
#ifdef GDBTK
      {"tclcommand", required_argument, 0, 'z'},
      {"enable-external-editor", no_argument, 0, 'y'},
      {"editor-command", required_argument, 0, 'w'},
#endif
      {"ui", required_argument, 0, 'i'},
      {"interpreter", required_argument, 0, 'i'},
      {"i", required_argument, 0, 'i'},
      {"directory", required_argument, 0, 'd'},
      {"d", required_argument, 0, 'd'},
      {"cd", required_argument, 0, 11},
      {"tty", required_argument, 0, 't'},
      {"baud", required_argument, 0, 'b'},
      {"b", required_argument, 0, 'b'},
      {"nw", no_argument, &use_windows, 0},
      {"nowindows", no_argument, &use_windows, 0},
      {"w", no_argument, &use_windows, 1},
      {"windows", no_argument, &use_windows, 1},
      {"statistics", no_argument, 0, 13},
      {"write", no_argument, &write_files, 1},
      {"args", no_argument, &set_args, 1},
/* Allow machine descriptions to add more options... */
#ifdef ADDITIONAL_OPTIONS
      ADDITIONAL_OPTIONS
#endif
      {0, no_argument, 0, 0}
    };

    while (1)
      {
	int option_index;

	c = getopt_long_only (argc, argv, "",
			      long_options, &option_index);
	if (c == EOF || set_args)
	  break;

	/* Long option that takes an argument.  */
	if (c == 0 && long_options[option_index].flag == 0)
	  c = long_options[option_index].val;

	switch (c)
	  {
	  case 0:
	    /* Long option that just sets a flag.  */
	    break;
	  case 10:
	    symarg = optarg;
	    execarg = optarg;
	    break;
	  case 11:
	    cdarg = optarg;
	    break;
	  case 12:
	    /* FIXME: what if the syntax is wrong (e.g. not digits)?  */
	    annotation_level = atoi (optarg);
	    break;
	  case 13:
	    /* Enable the display of both time and space usage.  */
	    display_time = 1;
	    display_space = 1;
	    break;
	  case 'f':
	    annotation_level = 1;
/* We have probably been invoked from emacs.  Disable window interface.  */
	    use_windows = 0;
	    break;
	  case 's':
	    symarg = optarg;
	    break;
	  case 'e':
	    execarg = optarg;
	    break;
	  case 'c':
	    corearg = optarg;
	    break;
	  case 'p':
	    /* "corearg" is shared by "--core" and "--pid" */
	    corearg = optarg;
	    break;
	  case 'x':
	    cmdarg[ncmd++] = optarg;
	    if (ncmd >= cmdsize)
	      {
		cmdsize *= 2;
		cmdarg = (char **) xrealloc ((char *) cmdarg,
					     cmdsize * sizeof (*cmdarg));
	      }
	    break;
#ifdef GDBTK
	  case 'z':
	    {
extern int gdbtk_test (char *);
	      if (!gdbtk_test (optarg))
		{
		  fprintf_unfiltered (gdb_stderr, _("%s: unable to load tclcommand file \"%s\""),
				      argv[0], optarg);
		  exit (1);
		}
	      break;
	    }
	  case 'y':
	    /* Backwards compatibility only.  */
	    break;
	  case 'w':
	    {
	      external_editor_command = xstrdup (optarg);
	      break;
	    }
#endif /* GDBTK */
	  case 'i':
	    interpreter_p = optarg;
	    break;
	  case 'd':
	    dirarg[ndir++] = optarg;
	    if (ndir >= dirsize)
	      {
		dirsize *= 2;
		dirarg = (char **) xrealloc ((char *) dirarg,
					     dirsize * sizeof (*dirarg));
	      }
	    break;
	  case 't':
	    ttyarg = optarg;
	    break;
	  case 'q':
	    quiet = 1;
	    break;
	  case 'b':
	    {
	      int i;
	      char *p;

	      i = strtol (optarg, &p, 0);
	      if (i == 0 && p == optarg)

		/* Don't use *_filtered or warning() (which relies on
		   current_target) until after initialize_all_files(). */

		fprintf_unfiltered
		  (gdb_stderr,
		   _("warning: could not set baud rate to `%s'.\n"), optarg);
	      else
		baud_rate = i;
	    }
            break;
	  case 'l':
	    {
	      int i;
	      char *p;

	      i = strtol (optarg, &p, 0);
	      if (i == 0 && p == optarg)

		/* Don't use *_filtered or warning() (which relies on
		   current_target) until after initialize_all_files(). */

		fprintf_unfiltered
		  (gdb_stderr,
		 _("warning: could not set timeout limit to `%s'.\n"), optarg);
	      else
		remote_timeout = i;
	    }
	    break;

#ifdef ADDITIONAL_OPTION_CASES
	    ADDITIONAL_OPTION_CASES
#endif
	  case '?':
	    fprintf_unfiltered (gdb_stderr,
			_("Use `%s --help' for a complete list of options.\n"),
				argv[0]);
	    exit (1);
	  }
      }

    /* If --help or --version, disable window interface.  */
    if (print_help || print_version)
      {
	use_windows = 0;
#ifdef TUI
	/* Disable the TUI as well.  */
	tui_version = 0;
#endif
      }

#ifdef TUI
    /* An explicit --tui flag overrides the default UI, which is the
       window system.  */
    if (tui_version)
      use_windows = 0;
#endif

    if (set_args)
      {
	/* The remaining options are the command-line options for the
	   inferior.  The first one is the sym/exec file, and the rest
	   are arguments.  */
	if (optind >= argc)
	  {
	    fprintf_unfiltered (gdb_stderr,
				_("%s: `--args' specified but no program specified\n"),
				argv[0]);
	    exit (1);
	  }
	symarg = argv[optind];
	execarg = argv[optind];
	++optind;
	set_inferior_args_vector (argc - optind, &argv[optind]);
      }
    else
      {
	/* OK, that's all the options.  The other arguments are filenames.  */
	count = 0;
	for (; optind < argc; optind++)
	  switch (++count)
	    {
	    case 1:
	      symarg = argv[optind];
	      execarg = argv[optind];
	      break;
	    case 2:
	      /* The documentation says this can be a "ProcID" as well. 
	         We will try it as both a corefile and a pid.  */
	      corearg = argv[optind];
	      break;
	    case 3:
	      fprintf_unfiltered (gdb_stderr,
				  _("Excess command line arguments ignored. (%s%s)\n"),
				  argv[optind], (optind == argc - 1) ? "" : " ...");
	      break;
	    }
      }
    if (batch)
      quiet = 1;
  }

  /* Initialize all files.  Give the interpreter a chance to take
     control of the console via the init_ui_hook()) */
  gdb_init (argv[0]);

  /* Do these (and anything which might call wrap_here or *_filtered)
     after initialize_all_files.  */
  if (print_version)
    {
      print_gdb_version (gdb_stdout);
      wrap_here ("");
      printf_filtered ("\n");
      exit (0);
    }

  if (print_help)
    {
      print_gdb_help (gdb_stdout);
      fputs_unfiltered ("\n", gdb_stdout);
      exit (0);
    }

  if (!quiet)
    {
      /* Print all the junk at the top, with trailing "..." if we are about
         to read a symbol file (possibly slowly).  */
      print_gdb_version (gdb_stdout);
      if (symarg)
	printf_filtered ("..");
      wrap_here ("");
      gdb_flush (gdb_stdout);	/* Force to screen during slow operations */
    }

  error_pre_print = "\n\n";
  quit_pre_print = error_pre_print;

  /* We may get more than one warning, don't double space all of them... */
  warning_pre_print = _("\nwarning: ");

  /* Read and execute $HOME/.gdbinit file, if it exists.  This is done
     *before* all the command line arguments are processed; it sets
     global parameters, which are independent of what file you are
     debugging or what directory you are in.  */
  homedir = getenv ("HOME");
  if (homedir)
    {
      homeinit = (char *) alloca (strlen (homedir) +
				  strlen (gdbinit) + 10);
      strcpy (homeinit, homedir);
      strcat (homeinit, "/");
      strcat (homeinit, gdbinit);

      if (!inhibit_gdbinit)
	{
	  catch_command_errors (source_command, homeinit, 0, RETURN_MASK_ALL);
	}

      /* Do stats; no need to do them elsewhere since we'll only
         need them if homedir is set.  Make sure that they are
         zero in case one of them fails (this guarantees that they
         won't match if either exists).  */

      memset (&homebuf, 0, sizeof (struct stat));
      memset (&cwdbuf, 0, sizeof (struct stat));

      stat (homeinit, &homebuf);
      stat (gdbinit, &cwdbuf);	/* We'll only need this if
				   homedir was set.  */
    }

  /* Now perform all the actions indicated by the arguments.  */
  if (cdarg != NULL)
    {
      catch_command_errors (cd_command, cdarg, 0, RETURN_MASK_ALL);
    }

  for (i = 0; i < ndir; i++)
    catch_command_errors (directory_command, dirarg[i], 0, RETURN_MASK_ALL);
  xfree (dirarg);

  if (execarg != NULL
      && symarg != NULL
      && STREQ (execarg, symarg))
    {
      /* The exec file and the symbol-file are the same.  If we can't
         open it, better only print one error message.
         catch_command_errors returns non-zero on success! */
      if (catch_command_errors (exec_file_attach, execarg, !batch, RETURN_MASK_ALL))
	catch_command_errors (symbol_file_add_main, symarg, 0, RETURN_MASK_ALL);
    }
  else
    {
      if (execarg != NULL)
	catch_command_errors (exec_file_attach, execarg, !batch, RETURN_MASK_ALL);
      if (symarg != NULL)
	catch_command_errors (symbol_file_add_main, symarg, 0, RETURN_MASK_ALL);
    }

  /* After the symbol file has been read, print a newline to get us
     beyond the copyright line...  But errors should still set off
     the error message with a (single) blank line.  */
  if (!quiet)
    printf_filtered ("\n");
  error_pre_print = "\n";
  quit_pre_print = error_pre_print;
  warning_pre_print = _("\nwarning: ");

  if (corearg != NULL)
    {
      /* corearg may be either a corefile or a pid.
	 If its first character is a digit, try attach first
	 and then corefile.  Otherwise try corefile first. */

      if (isdigit (corearg[0]))
	{
	  if (catch_command_errors (attach_command, corearg, 
				    !batch, RETURN_MASK_ALL) == 0)
	    catch_command_errors (core_file_command, corearg, 
				  !batch, RETURN_MASK_ALL);
	}
      else /* Can't be a pid, better be a corefile. */
	catch_command_errors (core_file_command, corearg, 
			      !batch, RETURN_MASK_ALL);
    }

  if (ttyarg != NULL)
    catch_command_errors (tty_command, ttyarg, !batch, RETURN_MASK_ALL);

#ifdef ADDITIONAL_OPTION_HANDLER
  ADDITIONAL_OPTION_HANDLER;
#endif

  /* Error messages should no longer be distinguished with extra output. */
  error_pre_print = NULL;
  quit_pre_print = NULL;
  warning_pre_print = _("warning: ");

  /* Read the .gdbinit file in the current directory, *if* it isn't
     the same as the $HOME/.gdbinit file (it should exist, also).  */

  if (!homedir
      || memcmp ((char *) &homebuf, (char *) &cwdbuf, sizeof (struct stat)))
    if (!inhibit_gdbinit)
      {
	catch_command_errors (source_command, gdbinit, 0, RETURN_MASK_ALL);
      }

  for (i = 0; i < ncmd; i++)
    {
#if 0
      /* NOTE: cagney/1999-11-03: SET_TOP_LEVEL() was a macro that
         expanded into a call to setjmp().  */
      if (!SET_TOP_LEVEL ()) /* NB: This is #if 0'd out */
	{
	  /* NOTE: I am commenting this out, because it is not clear
	     where this feature is used. It is very old and
	     undocumented. ezannoni: 1999-05-04 */
#if 0
	  if (cmdarg[i][0] == '-' && cmdarg[i][1] == '\0')
	    read_command_file (stdin);
	  else
#endif
	    source_command (cmdarg[i], !batch);
	  do_cleanups (ALL_CLEANUPS);
	}
#endif
      catch_command_errors (source_command, cmdarg[i], !batch, RETURN_MASK_ALL);
    }
  xfree (cmdarg);

  /* Read in the old history after all the command files have been read. */
  init_history ();

  if (batch)
    {
      /* We have hit the end of the batch file.  */
      exit (0);
    }

  /* Do any host- or target-specific hacks.  This is used for i960 targets
     to force the user to set a nindy target and spec its parameters.  */

#ifdef BEFORE_MAIN_LOOP_HOOK
  BEFORE_MAIN_LOOP_HOOK;
#endif

  END_PROGRESS (argv[0]);

  /* Show time and/or space usage.  */

  if (display_time)
    {
      long init_time = get_run_time () - time_at_startup;

      printf_unfiltered (_("Startup time: %ld.%06ld\n"),
			 init_time / 1000000, init_time % 1000000);
    }

  if (display_space)
    {
#ifdef HAVE_SBRK
      extern char **environ;
      char *lim = (char *) sbrk (0);

      printf_unfiltered (_("Startup size: data size %ld\n"),
			 (long) (lim - (char *) &environ));
#endif
    }

#if 0
  /* FIXME: cagney/1999-11-06: The original main loop was like: */
  while (1)
    {
      if (!SET_TOP_LEVEL ())
	{
	  do_cleanups (ALL_CLEANUPS);	/* Do complete cleanup */
	  /* GUIs generally have their own command loop, mainloop, or whatever.
	     This is a good place to gain control because many error
	     conditions will end up here via longjmp(). */
	  if (command_loop_hook)
	    command_loop_hook ();
	  else
	    command_loop ();
	  quit_command ((char *) 0, instream == stdin);
	}
    }
  /* NOTE: If the command_loop() returned normally, the loop would
     attempt to exit by calling the function quit_command().  That
     function would either call exit() or throw an error returning
     control to SET_TOP_LEVEL. */
  /* NOTE: The function do_cleanups() was called once each time round
     the loop.  The usefulness of the call isn't clear.  If an error
     was thrown, everything would have already been cleaned up.  If
     command_loop() returned normally and quit_command() was called,
     either exit() or error() (again cleaning up) would be called. */
#endif
  /* NOTE: cagney/1999-11-07: There is probably no reason for not
     moving this loop and the code found in captured_command_loop()
     into the command_loop() proper.  The main thing holding back that
     change - SET_TOP_LEVEL() - has been eliminated. */
  while (1)
    {
      catch_errors (captured_command_loop, 0, "", RETURN_MASK_ALL);
    }
  /* No exit -- exit is through quit_command.  */
}
Example #24
0
int main() {
  solutionp root;
  root = parse();

  while(command_loop(root));
}
int main(int argc, char *argv[]) {
    base::CommandLine::Init(argc, argv);
    base::CommandLine* cl = base::CommandLine::ForCurrentProcess();

    int32_t port = kDefaultPort;
    if (cl->HasSwitch(kPort)) {
        std::string value = cl->GetSwitchValueASCII(kPort);
        base::StringToInt(value, &port);
    }

    // Puch a TCP hole to accept connection
    FwDaemon daemon(std::unique_ptr<FirewallInterface>{new FirewalldFirewall()}, (uint16_t)port);
    daemon.Run();

    std::unique_ptr<Socket> server = Socket::NewServer(Socket::Protocol::kTcp, port);
    if (server == nullptr) {
        ALOGE("Failed to create fastbootd service.");
        return 1;
    }

    int fastbootd_reboot = 0;
    if (property_get_bool("persist.sys.fastbootd.reboot", 1)) {
        pthread_t hreboot;
        pthread_create(&hreboot, NULL, thread_reboot, &fastbootd_reboot);
        fastbootd_reboot = 1;
    }

    // Check if in demo mode
    if (fastbootd_reboot == 1) {
        struct stat st;
        int result = stat("/boot/DEMO", &st);
        if (result == 0 && S_ISREG(st.st_mode)) {
            fastbootd_reboot = 0;
        }
    }

    std::string handshake_message(android::base::StringPrintf("FB%02d", kProtocolVersion));
    while (true) {
        std::unique_ptr<Socket> client = server->Accept();
        if (client == nullptr) {
            ALOGE("Failed to accept client connection.");
            continue;
        }

        char buffer[4];
        ssize_t bytes = client->Receive(buffer, sizeof(buffer), 500);
        if (bytes != 4) {
            ALOGE("Failed to get client version.");
            continue;
        }

        if (memcmp(buffer, "FB01", 4) != 0) {
            ALOGE("Unsupported client: %c%c%c%c", buffer[0], buffer[1], buffer[2], buffer[3]);
            continue;
        }

        if (fastbootd_reboot) {
            fastbootd_reboot = 0;
            property_set("persist.sys.fastbootd.reboot", "0");
        }

        if (!client->Send(handshake_message.c_str(), kHandshakeLength)) {
            ALOGE("Failed to send handshake.");
            continue;
        }

        command_loop(client.get());
    }

    return 0;
}
Example #26
0
File: command.cpp Project: att/uwin
void process_commands(string &s, const char *file, int lineno)
{
  input_stack::init();
  input_stack::push_string(s, file, lineno);
  command_loop();
}
Example #27
0
int main(int argc, char **argv)
{
    int readonly = 0;
    int growable = 0;
    const char *sopt = "hVc:rsnmgk";
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "offset", 1, NULL, 'o' },
        { "cmd", 1, NULL, 'c' },
        { "read-only", 0, NULL, 'r' },
        { "snapshot", 0, NULL, 's' },
        { "nocache", 0, NULL, 'n' },
        { "misalign", 0, NULL, 'm' },
        { "growable", 0, NULL, 'g' },
        { "native-aio", 0, NULL, 'k' },
        { NULL, 0, NULL, 0 }
    };
    int c;
    int opt_index = 0;
    int flags = 0;

    progname = basename(argv[0]);

    while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
        switch (c) {
        case 's':
            flags |= BDRV_O_SNAPSHOT;
            break;
        case 'n':
            flags |= BDRV_O_NOCACHE;
            break;
        case 'c':
            add_user_command(optarg);
            break;
        case 'r':
            readonly = 1;
            break;
        case 'm':
            misalign = 1;
            break;
        case 'g':
            growable = 1;
            break;
        case 'k':
            flags |= BDRV_O_NATIVE_AIO;
            break;
        case 'V':
            printf("%s version %s\n", progname, VERSION);
            exit(0);
        case 'h':
            usage(progname);
            exit(0);
        default:
            usage(progname);
            exit(1);
        }
    }

    if ((argc - optind) > 1) {
        usage(progname);
        exit(1);
    }

    bdrv_init();

    /* initialize commands */
    quit_init();
    help_init();
    add_command(&open_cmd);
    add_command(&close_cmd);
    add_command(&read_cmd);
    add_command(&readv_cmd);
    add_command(&write_cmd);
    add_command(&writev_cmd);
    add_command(&multiwrite_cmd);
    add_command(&aio_read_cmd);
    add_command(&aio_write_cmd);
    add_command(&aio_flush_cmd);
    add_command(&flush_cmd);
    add_command(&truncate_cmd);
    add_command(&length_cmd);
    add_command(&info_cmd);
    add_command(&alloc_cmd);

    add_args_command(init_args_command);
    add_check_command(init_check_command);

    /* open the device */
    if (!readonly) {
        flags |= BDRV_O_RDWR;
    }

    if ((argc - optind) == 1)
        openfile(argv[optind], flags, growable);
    command_loop();

    /*
     * Make sure all outstanding requests get flushed the program exits.
     */
    qemu_aio_flush();

    if (bs)
        bdrv_close(bs);
    return 0;
}
Example #28
0
int main(int argc, char **argv)
{
    int readonly = 0;
    int growable = 0;
    const char *sopt = "hVc:d:rsnmgkt:T:";
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "offset", 1, NULL, 'o' },
        { "cmd", 1, NULL, 'c' },
        { "read-only", 0, NULL, 'r' },
        { "snapshot", 0, NULL, 's' },
        { "nocache", 0, NULL, 'n' },
        { "misalign", 0, NULL, 'm' },
        { "growable", 0, NULL, 'g' },
        { "native-aio", 0, NULL, 'k' },
        { "discard", 1, NULL, 'd' },
        { "cache", 1, NULL, 't' },
        { "trace", 1, NULL, 'T' },
        { NULL, 0, NULL, 0 }
    };
    int c;
    int opt_index = 0;
    int flags = BDRV_O_UNMAP;

    progname = basename(argv[0]);

    while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
        switch (c) {
        case 's':
            flags |= BDRV_O_SNAPSHOT;
            break;
        case 'n':
            flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
            break;
        case 'd':
            if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
                error_report("Invalid discard option: %s", optarg);
                exit(1);
            }
            break;
        case 'c':
            add_user_command(optarg);
            break;
        case 'r':
            readonly = 1;
            break;
        case 'm':
            misalign = 1;
            break;
        case 'g':
            growable = 1;
            break;
        case 'k':
            flags |= BDRV_O_NATIVE_AIO;
            break;
        case 't':
            if (bdrv_parse_cache_flags(optarg, &flags) < 0) {
                error_report("Invalid cache option: %s", optarg);
                exit(1);
            }
            break;
        case 'T':
            if (!trace_backend_init(optarg, NULL)) {
                exit(1); /* error message will have been printed */
            }
            break;
        case 'V':
            printf("%s version %s\n", progname, VERSION);
            exit(0);
        case 'h':
            usage(progname);
            exit(0);
        default:
            usage(progname);
            exit(1);
        }
    }

    if ((argc - optind) > 1) {
        usage(progname);
        exit(1);
    }

    qemu_init_main_loop();
    bdrv_init();

    /* initialize commands */
    quit_init();
    help_init();
    add_command(&open_cmd);
    add_command(&close_cmd);
    add_command(&read_cmd);
    add_command(&readv_cmd);
    add_command(&write_cmd);
    add_command(&writev_cmd);
    add_command(&multiwrite_cmd);
    add_command(&aio_read_cmd);
    add_command(&aio_write_cmd);
    add_command(&aio_flush_cmd);
    add_command(&flush_cmd);
    add_command(&truncate_cmd);
    add_command(&length_cmd);
    add_command(&info_cmd);
    add_command(&discard_cmd);
    add_command(&alloc_cmd);
    add_command(&map_cmd);
    add_command(&break_cmd);
    add_command(&resume_cmd);
    add_command(&wait_break_cmd);
    add_command(&abort_cmd);

    add_args_command(init_args_command);
    add_check_command(init_check_command);

    /* open the device */
    if (!readonly) {
        flags |= BDRV_O_RDWR;
    }

    if ((argc - optind) == 1) {
        openfile(argv[optind], flags, growable);
    }
    command_loop();

    /*
     * Make sure all outstanding requests complete before the program exits.
     */
    bdrv_drain_all();

    if (bs) {
        bdrv_delete(bs);
    }
    return 0;
}
Example #29
0
File: iwatch.c Project: iij/iwatch
int
main(int argc, char *argv[])
{
	int	 i, ch, cmdsiz = 0;
	char	*e, *s;
	double	 intvl;

	setlocale(LC_ALL, "");
	/*
	 * Command line option handling
	 */
	while ((ch = getopt(argc, argv, "+i:rewps:c:x")) != -1)
		switch (ch) {
		case 'i':
			intvl = strtod(optarg, &e);
			if (*optarg == '\0' || *e != '\0')
				errx(EX_USAGE, "invalid interval: %s", optarg);
			if (*optarg == '-')
				errx(EX_USAGE, "interval must be positive: %s",
					optarg);
			opt_interval.tv_sec = (int)intvl;
			opt_interval.tv_usec = (u_long)
			    (intvl * 1000000UL) % 1000000UL;
			break;
		case 'r':
			reverse_mode = REVERSE_CHAR;
			break;
		case 'w':
			reverse_mode = REVERSE_WORD;
			break;
		case 'e':
			reverse_mode = REVERSE_LINE;
			break;
		case 'p':
			pause_status = 1;
			break;
		case 's':
			start_line = atoi(optarg);
			break;
		case 'c':
			start_column = atoi(optarg);
			break;
		case 'x':
			xflag = 1;
			break;
		default:
			usage();
			exit(EX_USAGE);
		}
	argc -= optind;
	argv += optind;

	/*
	 * Build command string to give to popen
	 */
	if (argc <= 0) {
		usage();
		exit(EX_USAGE);
	}

	if ((cmdv = calloc(argc + 1, sizeof(char *))) == NULL)
		err(EX_OSERR, "calloc");

	cmdstr = "";
	for (i = 0; i < argc; i++) {
		cmdv[i] = argv[i];
		while (strlen(cmdstr) + strlen(argv[i]) + 3 > cmdsiz) {
			if (cmdsiz == 0) {
				cmdsiz = 128;
				s = calloc(cmdsiz, 1);
			} else {
				cmdsiz *= 2;
				s = realloc(cmdstr, cmdsiz);
			}
			if (s == NULL)
				err(EX_OSERR, "malloc");
			cmdstr = s;
		}
		if (i != 0)
			strlcat(cmdstr, " ", cmdsiz);
		strlcat(cmdstr, argv[i], cmdsiz);
	}
	cmdv[i++] = NULL;

	/*
	 * Initialize signal
	 */
	(void) signal(SIGINT, on_signal);
	(void) signal(SIGTERM, on_signal);
	(void) signal(SIGHUP, on_signal);

	/*
	 * Initialize curses environment
	 */
	initscr();
	start_color();
	use_default_colors();
	parse_style();
	noecho();
	crmode();

	/*
	 * Enter main processing loop and never come back here
	 */
	command_loop();

	/* NOTREACHED */
	abort();
}