コード例 #1
0
ファイル: ep_appcom.c プロジェクト: MenglongWu/EpollServerX
int ThreadRunServerAndShell(struct ep_t *pep)
{
	rl_bind_key('?',funtest2);
	initialize_readline();
	tms_Init();
	tms_Callback(&tcb);
    ep_Interface(pep, 2);           // 初始化ep接口
    ep_Callback(pep);               // 设在epollserver在本工程的回掉函数

#ifdef _MANAGE
    if(ep_Listen(pep,6000)) {     // 监听TCP 0.0.0.0:6500端口
        return 0;
    }
#else
	if(ep_Listen(pep,6500)) {     // 监听TCP 0.0.0.0:6500端口
        return 0;
    }
#endif
    
    ep_RunServer(pep);             // 运行epollserver线程
    
	
    pthread_create(&g_pthreadshell,NULL,ThreadShell,pep);
    pthread_create(&g_pthreadconnect_cu,NULL,ThreadConnectCU,pep);
    
    return 0;
}
コード例 #2
0
ファイル: console.c プロジェクト: PopulusHuang/SFTP-SYS
int console(SSL *ssl)
{
  char *line, *s;

  CMDSSL=ssl;
  initialize_readline ();       /* Bind our completer. */

  line = (char *)NULL;
  /* Loop reading and executing lines until the user quits. */
  for ( ; DONE == 0; )
    {

      line = readline ("SFTP>> ");
      if (!line) /* line == NULL */
        break;

      /* Remove leading and trailing whitespace(before command) from the line.
         Then, if there is anything left, add it to the history list
         and execute it. */
      s = strip_white (line);

      if (*s)
        {
          add_history (s);/* add the command to history */
          execute_line (s);
        }
      free (line);
    }
  return 0;
}
コード例 #3
0
ファイル: voyageur.c プロジェクト: Armael/voyageur
int main() {
  char *s, *line;

  printf(MESSAGE);

  env_resetTowns(&env);

  initialize_readline();

  while(env.done == 0) {
    char prompt[40];
    if(env.cur_towns->nb) {
      snprintf(prompt, 40, "(%d towns) %s>%s ", env.cur_towns->nb,
	       ANSI_GREEN, ANSI_NORMAL);
    } else {
      snprintf(prompt, 40, "%s>%s ", ANSI_GREEN, ANSI_NORMAL);
    }

    line = readline(prompt);
    
    if(line) {
      s = stripwhite(line);

      if(s[0] != '\0') {
	add_history(s);
	execute_line(s);
      }
      
      free(line);
    }
  }

  return 0;
}
コード例 #4
0
ファイル: cli.c プロジェクト: lperkov/libsysrepo
int main (int argc, char **argv)
{
  extern int sockfd;
  char *line, *s;
  struct sigaction sig;
  memset(&sig,'\0',sizeof(sig));
 
  /* Use the sa_sigaction field because the handles has two additional parameters */
  sig.sa_sigaction = &handle_signal; 
  /* The SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler. */
  sig.sa_flags = SA_SIGINFO; 
  if (sigaction(SIGPIPE, &sig, NULL) < 0) {
    fprintf (stderr,"SIGPIPE sigaction failure");
    return 1;
  }
  if (sigaction(SIGINT, &sig, NULL) < 0) {
    fprintf (stderr,"SIGINT sigaction failure");
    return 1;
  }

  progname = argv[0];

  initialize_readline ();/* Bind our completer. */

  char *lineptr = NULL;
  /* Loop reading and executing lines until the user quits. */
  for ( ; done == 0; )
    {
      if (!lineptr)
	{
	  if (!(line = readline("sysrepo> "))) 
	    break;
	  lineptr = strtok(line, ";");
	}

      printf("line is %s\n",line);

      /* Remove leading and trailing whitespace from the line.
         Then, if there is anything left, add it to the history list
         and execute it. */
      s = stripwhite (lineptr);

      if (*s)
        {
          add_history (s);
          execute_line (s);
        }
      lineptr = strtok(NULL,";");
      if(!lineptr)
	free (line);
    }
  close(sockfd);
  exit (0);
}
コード例 #5
0
ファイル: input.c プロジェクト: AXLEproject/postgres
/*
 * Put any startup stuff related to input in here. It's good to maintain
 * abstraction this way.
 *
 * The only "flag" right now is 1 for use readline & history.
 */
void
initializeInput(int flags)
{
#ifdef USE_READLINE
	if (flags & 1)
	{
		const char *histfile;
		char		home[MAXPGPATH];

		useReadline = true;
		initialize_readline();

		useHistory = true;
		using_history();
		history_lines_added = 0;

		histfile = GetVariable(pset.vars, "HISTFILE");

		if (histfile == NULL)
		{
			char	   *envhist;

			envhist = getenv("PSQL_HISTORY");
			if (envhist != NULL && strlen(envhist) > 0)
				histfile = envhist;
		}

		if (histfile == NULL)
		{
			if (get_home_path(home))
			{
				psql_history = pg_malloc(strlen(home) + 1 +
										 strlen(PSQLHISTORY) + 1);
				snprintf(psql_history, MAXPGPATH, "%s/%s", home, PSQLHISTORY);
			}
		}
		else
		{
			psql_history = pg_strdup(histfile);
			expand_tilde(&psql_history);
		}

		if (psql_history)
		{
			read_history(psql_history);
			decode_history();
		}
	}
#endif

	atexit(finishInput);
}
コード例 #6
0
ファイル: fileman.c プロジェクト: AbrahamJewowich/FreeSWITCH
int
main (int argc, char **argv)
{
   char *line, *s;

   progname = argv[0];

   initialize_readline();       /* Bind our completer. */

   stifle_history(7);

   /* Loop reading and executing lines until the user quits. */
   for ( ; done == 0; )
   {
      line = readline ("FileMan: ");

      if (!line)
         break;

      /* Remove leading and trailing whitespace from the line.
         Then, if there is anything left, add it to the history list
         and execute it. */
      s = stripwhite(line);

      if (*s) {

         char* expansion;
         int result;

         result = history_expand(s, &expansion);

         if (result < 0 || result == 2) {
            fprintf(stderr, "%s\n", expansion);
         } else {
            add_history(expansion);
            execute_line(expansion);
         }
         free(expansion);
      }

      free(line);
   }
   exit (0);

   return 0;
}
コード例 #7
0
ファイル: input.c プロジェクト: berkeley-cs186/course-fa07
/*
 * Put any startup stuff related to input in here. It's good to maintain
 * abstraction this way.
 *
 * The only "flag" right now is 1 for use readline & history.
 */
void
initializeInput(int flags)
{
#ifdef USE_READLINE
	if (flags & 1)
	{
		const char *histfile;
		char		home[MAXPGPATH];

		useReadline = true;
		initialize_readline();

		useHistory = true;
		using_history();

		histfile = GetVariable(pset.vars, "HISTFILE");
		if (histfile == NULL)
		{
			if (get_home_path(home))
			{
				psql_history = pg_malloc(strlen(home) + 1 +
										 strlen(PSQLHISTORY) + 1);
				snprintf(psql_history, MAXPGPATH, "%s/%s", home, PSQLHISTORY);
			}
		}
		else
		{
			psql_history = pg_strdup(histfile);
			expand_tilde(&psql_history);
		}

		if (psql_history)
		{
			read_history(psql_history);
			decode_history();
		}
	}
#endif

#ifdef HAVE_ATEXIT
	atexit(finishInput);
#else
	on_exit(finishInput, NULL);
#endif
}
コード例 #8
0
ファイル: main.c プロジェクト: sohaibafifi/Minishell
////===========================================================================================
int main() {
    /* installation du handler pour le signal child_signal */
    struct sigaction sig;
    sig.sa_flags = 0;
    sig.sa_handler = child_signal;
    sigemptyset(&sig.sa_mask);
    sigaction(child_signal,&sig,NULL);

    /* désactivation l'interruption par Contrôle+C */
    sig.sa_handler = SIG_IGN;
    sigaction(SIGINT, &sig, NULL);

    initialize_readline ();
    using_history ();

    printf("Lecture de fichier d'histoire : (%s)\n",strerror(read_history (history_filename)));

    while (!Exit) {
        init();
        prompt();
        next=0;
        lire();
        decoupe_ligne_seq();
        int i=0;
        for (;i<numcmd_seq;i++) {
            char *line;
            char* elem[MAXELEMS];
            //strcpy(&line,cmds_seq[i]);
            decoupe_ligne_pipe(cmds_seq[i]);
            if (piped) {
                runPipe();
            } else {
                decoupe_cmd(cmds_seq[i],elem);
                if (redirected) {
                    runRedirectedCommand(elem,red_file,red_type);
                } else {
                    execute(elem);
                }
            }
        }
    }
    printf("Sauvegarde de fichier d'histoire : (%s)\n",strerror(write_history(history_filename)));
    return 0;
}
コード例 #9
0
ファイル: gsl-shell-jit.c プロジェクト: LuaDist/gsl-shell
int main(int argc, char **argv)
{
    int status;
#ifdef USE_READLINE
    initialize_readline();
#endif
    gsl_shell_init(gsl_shell);
    gsl_shell_open(gsl_shell);

    pthread_mutex_lock(&gsl_shell->exec_mutex);

    smain.argc = argc;
    smain.argv = argv;
    status = lua_cpcall(gsl_shell->L, pmain, NULL);
    report(gsl_shell->L, status);

    pthread_mutex_unlock(&gsl_shell->exec_mutex);

    gsl_shell_close_with_graph(gsl_shell, !smain.keep_windows);
    gsl_shell_free(gsl_shell);

    return (status || smain.status) ? EXIT_FAILURE : EXIT_SUCCESS;
}
コード例 #10
0
ファイル: console.c プロジェクト: BGCX262/zxnz-svn-to-git
int main()
{
    printf("***************************************************************\n");
    printf("                         CONSOLE                               \n");
    printf("***************************************************************\n");
    printf("To get help, please type \"help\"\n");

    char *line, *s;
    initialize_readline();

    while (1) {
        line = readline("> ");
        if (!line)
            break;
        s = g_strstrip(line);
        if (*s) {
            add_history(s);
            execute_line(s);
        }

    }
    return 0;
}
コード例 #11
0
ファイル: input.c プロジェクト: sunyangkobe/cscd43
/*
 * Put any startup stuff related to input in here. It's good to maintain
 * abstraction this way.
 *
 * The only "flag" right now is 1 for use readline & history.
 */
void
initializeInput(int flags)
{
#ifdef USE_READLINE
	if (flags & 1)
	{
		const char *home;

		useReadline = true;
		initialize_readline();

		useHistory = true;
		if (GetVariable(pset.vars, "HISTSIZE") == NULL)
			SetVariable(pset.vars, "HISTSIZE", "500");
		using_history();
		home = getenv("HOME");
		if (home)
		{
			char	   *psql_history = (char *) malloc(strlen(home) + 1 +
												strlen(PSQLHISTORY) + 1);

			if (psql_history)
			{
				sprintf(psql_history, "%s/%s", home, PSQLHISTORY);
				read_history(psql_history);
				free(psql_history);
			}
		}
	}
#endif

#ifdef HAVE_ATEXIT
	atexit(finishInput);
#else
	on_exit(finishInput, NULL);
#endif
}
コード例 #12
0
ファイル: main.c プロジェクト: saeidw/Agros
int main (){
    int pid = 0;
    command_t cmd = {NULL, 0, {NULL}};
    char *commandline = (char *)NULL;
    char* username = NULL;
    config_t ag_config;
    int bg_cmd = AG_FALSE;
    char prompt[MAX_LINE_LEN];

    /* Sets the username */
    set_username (&username);

    /* Opens the syslog file */
    openlog (username, LOG_PID, LOG_USER);

    /* Parses the config files for data */
    parse_config (&ag_config, username);

    /* Initializes GNU Readline */
    initialize_readline(&ag_config);

    /*
     *   Main loop:
     *   - print prompt
     *   - read input and parse it
     *   - either a built-in command ("cd", "?" or "exit)
     *   - or a system command, in which case the program forks and executes it with execvp()
     */

    if (ag_config.welcome_message != NULL && strlen (ag_config.welcome_message) > 0) {
        fprintf (stdout, "\n%s\n\n", ag_config.welcome_message);
    }

    while (AG_TRUE){
	/* Set the prompt */
	get_prompt(prompt, MAX_LINE_LEN, username);

	/* 
	 * Read a line of input 
	 * commandline should be deallocated with free() 
	 */
	commandline = read_input (prompt);

        parse_command (commandline, &cmd);

        switch (get_cmd_code (cmd.name)){
            case EMPTY_CMD:
   	            break;

            case CD_CMD:
                change_directory (cmd.argv[1], ag_config.loglevel);
   	            break;

            case HELP_CMD:
                print_help(&ag_config);
   	            break;

            case ENV_CMD:
   	            print_env (cmd.argv[1]);
   	            break;

            case EXIT_CMD:
		free (commandline);
		commandline = (char *)NULL;
                closelog ();
   	            return 0;

            case OTHER_CMD:

                /* Determines whether the command should run in the bg or not */
                bg_cmd = runs_in_background (&cmd);
                pid = vfork();

   	            if (pid == 0){
                if (!check_validity (cmd, ag_config)){
                    if (ag_config.loglevel == 3)    syslog (LOG_NOTICE, "Using command: %s.", cmd.name);
                    execvp (cmd.argv[0], cmd.argv);
   	        	    fprintf (stderr, "%s: Could not execute command!\nType '?' for help.\n", cmd.name);
                    if (ag_config.loglevel >= 2)    syslog (LOG_NOTICE, "Could not execute: %s.", cmd.name);
                }else {
   	        	    fprintf (stdout, "Not allowed! \n");
                    if (ag_config.warnings >= 0)    decrease_warnings (&ag_config);
                    if (ag_config.loglevel >= 1)    syslog (LOG_ERR, "Trying to use forbidden command: %s.", cmd.name);
                }

                _exit(EXIT_FAILURE);
   	            }else if (pid < 0){
                    fprintf (stderr, "Error! ... Negative PID. God knows what that means ...\n");
                    if (ag_config.loglevel >= 1) syslog (LOG_ERR, "Negative PID. Using command: %s.", cmd.name);
   	            }else {
                    if (!bg_cmd)
                        wait (0);
   	            }
   	            break;
        }

	free (commandline);
	commandline = (char *)NULL;
    }

    if (commandline)
	free (commandline);
    closelog();
    return 0;
}
コード例 #13
0
ファイル: main.c プロジェクト: NurKaynar/hacklab
int 
main(int argc, char *argv[], char *envp[])
{
  char *line;

  int returnValue;

	int i, fd;

	char *pathString = (char *)malloc(sizeof(char) * 256);
	char *cmd = (char *)malloc(sizeof(char) * 256);

  bzero(pathString, 256);
  bzero(cmd, 256);

  /* Manage Signals */
  signal(SIGINT, SIG_IGN);	
  signal(SIGQUIT,SIG_IGN);
//  signal(SIGCHLD,SIG_IGN);
  signal(SIGKILL,SIG_IGN);
  signal(SIGTERM,SIG_IGN);

	signal(SIGINT, handleSignal);

  /* Extract the PATH= var from envp */
	getPathString(envp, pathString);
  /* Insert each path to be searched into searchPath[][] */
  insertPathStringToSearch(searchPath, pathString);

  /* Print about Slash */
  clrScreen(argv, envp);
  printf("%s", aboutSlash);
  printf("PID=%d\n", getpid());

#if SLASH_DEBUG
  for(i=0; envp[i] != NULL; i++)
    printf("%s\n", envp[i]);
#endif

  /* Bind our completer + History Feature */
  initialize_readline();

  while(1)
  {
    line = readline ("\x1b[96m<$lash/>\x1b[00m "); /* Print in Red! */

    #if SLASH_DEBUG
      printf("Input: %s\n", line);
    #endif

    if(*line)
    {
      add_history (line);
      returnValue = execute_line (line);

      if(returnValue == CMD_EXIT)
        break;

      if(returnValue == CMD_UNKNOWN)
      {
        #if SLASH_DEBUG
          printf("CMD_UNKNOWN: %s\n", line);
        #endif
        /* Extract args to command into slashArgv[][] */
        nullifyArgv(slashArgv);
        fillArgv(line, slashArgv);
        bzero(cmd, 256);
				strncpy(cmd, slashArgv[0], strlen(slashArgv[0]));
				strncat(cmd, "\0", 1);

        #if SLASH_DEBUG
          printf("arg[0]: %s\n", slashArgv[0]);
          printf("cmd: %s\n", cmd);
        #endif

				if(index(cmd, '/') == NULL) 
        {
				  if(attachPath(cmd, searchPath) == 0) 
          {
					  callFork(cmd, slashArgv, envp);
					} 
          else 
					  printf("%s: command not found\n", cmd);
        } 
        else 
        {
				  if((fd = open(cmd, O_RDONLY)) > 0) 
          {
					  close(fd);
						callFork(cmd, slashArgv, envp);
					} 
          else 
					  printf("%s: command not found\n", cmd);
			  }
        freeArgv(slashArgv);
      }
    }

    if(line != NULL)
    free(line);
	  fflush(stdout);
  }

  free(cmd);
	free(pathString);
	for(i=0;i<50;i++)
		free(searchPath[i]);
	return 0;
}
コード例 #14
0
ファイル: occtl.c プロジェクト: fridex/ocserv
int main(int argc, char **argv)
{
	char *line = NULL;
	CONN_TYPE *conn;
	const char *file = NULL;
	void *gl_pool;
	cmd_params_st params;

	memset(&params, 0, sizeof(params));

	gl_pool = talloc_init("occtl");
	if (gl_pool == NULL) {
		fprintf(stderr, "talloc init error\n");
		exit(1);
	}

	ocsignal(SIGPIPE, SIG_IGN);

	if (argc > 1) {
		while (argc > 1 && argv[1][0] == '-') {
			if (argv[1][1] == 'j'
			    || (argv[1][1] == '-' && argv[1][2] == 'j')) {
				params.json = 1;

				argv += 1;
				argc -= 1;

			} else if (argv[1][1] == 'n'
			    || (argv[1][1] == '-' && argv[1][2] == 'n')) {
				params.no_pager = 1;

				argv += 1;
				argc -= 1;

			} else if (argv[1][1] == 'v'
			    || (argv[1][1] == '-' && argv[1][2] == 'v')) {
				version();
				exit(0);
			} else if (argc > 2 && (argv[1][1] == 's'
			    || (argv[1][1] == '-' && argv[1][2] == 's'))) {
				file = talloc_strdup(gl_pool, argv[2]);

				if (argc == 3) {
					goto interactive;
				}

				argv += 2;
				argc -= 2;
			} else {
				usage();
				exit(0);
			}
  		}

  		/* handle all arguments as a command */
		exit(single_cmd(argc, argv, gl_pool, file, &params));
	}

 interactive:
	conn = conn_init(gl_pool, file);

	initialize_readline();

	version();
	for (;;) {
		line = rl_gets(line);
		if (line == NULL)
			return 0;

		handle_cmd(conn, line, 0);
	}

	conn_close(conn);

	return 0;
}
コード例 #15
0
ファイル: ps4sh.c プロジェクト: Mistawes/ps4link
int main(int argc, char* argv[])
{
	

	//declare variables
    int ret;
    // poll client stuff
    int i, j, maxi, connfd, sockfd;
    int maxfd;
    struct sockaddr_in cliaddr;
    struct timeval clienttimeout;
    int nready;
    socklen_t clilen;
    //
    int client[MAX_CLIENTS];
    fd_set master_set, readset, clientset;
    VERBOSE = 0;
    printf("ps4sh version %s\n",PS4SH_VERSION);
	//call read config if exist we need redefine syntax and variables
    read_config();
	//if we call ps4sh with parameter it is the ps4 ip copy it to proper variable
    if (argc == 2) {
        strcpy(dst_ip, argv[1]);
        dst_ip[strlen(argv[1])] = '\0';
    }
    clienttimeout.tv_sec = 0;
    clienttimeout.tv_usec = USEC;
	
	
	// create request socket connected to ps4link fio service
	printf("Connecting to fio ps4link ip %s ", dst_ip);
	
	request_socket = ps4link_fio_listener(dst_ip, SRV_PORT, 60);
	if (request_socket < 0) {
		printf(", failed\n");
		return 1;
	}
	
	//udp socket to send commands to ps4
	command_socket = network_connect(dst_ip, 0x4712, SOCK_DGRAM);
	if (command_socket < 0) {
		printf(", failed\n");
		return 1;
	}
	
    // client stuff
	for(i = 0; i < MAX_CLIENTS; i++) {
		client[i] = -1;
	}
	FD_ZERO(&clientset);
	// end client stuff

	printf("\n");

	//create console log udp socket bind to 0.0.0.0

	console_socket = ps4link_log_listener(src_ip, LOG_PORT);

	if ( console_socket < 0 ) {
		perror("");
		printf("Unable to start log service!\n");
		//if i can't create local udp socket listening in LOG_PORT exit
		return 1;
	}
	//create ps4sh listener to let tools from third parties connect to ps4sh
	ps4sh_socket = ps4link_srv_setup(src_ip, SRV_PORT);
	if ( ps4sh_socket < 0 ) {
		perror("");
		printf("Unable to start command server!\n");
		//if i can't create local tcp socket listening in SRV_PORT exit
		return 1;
	}
	//populate set  standard output, command listener connected to ps4, udp logs listener, local command listener
	FD_ZERO(&master_set);
	//standard output
	FD_SET(0, &master_set);
	//ps4link fio channel
	FD_SET(request_socket, &master_set);
	//udp log channel
	FD_SET(console_socket, &master_set);
	//ps4sh channel
	FD_SET(ps4sh_socket, &master_set);
	client[0] = 0;
	client[1] = request_socket;
	client[2] = console_socket;
	client[3] = ps4sh_socket;
	maxfd = ps4sh_socket;
	maxi = 3;
	
	
	//initilize readline
	initialize_readline();
	debugNetPrintf(INFO,"Ready\n");
    
	//mail loop
	while(doloop) {
		readset = master_set;
		ret = select(maxfd+1, &readset, NULL, NULL, NULL);
		if ( ret < 0 )
		{
			if ( FD_ISSET(0, &readset) ) {
				continue;
			}
			debugNetPrintf(ERROR,"In select %s\n",strerror(errno));
			break;
		} 
		else if (ret == 0) 
		{
			/* no file desc are ready, lets move on in life */
		} 
		else 
		{
			for(i = 0; i <= maxi; i++) 
			{
				if ( (sockfd = client[i]) < 0) 
				{
					continue;
				}
				if ( !FD_ISSET(sockfd, &readset) ) 
				{
					continue;
				}
				//if we have udp log messages from ps4 debugnet
				if ( sockfd == console_socket) {
					ps4sh_log_read(console_socket);
				} 
				//if we have local standard  messages
				else if (sockfd == 0) 
				{
					rl_callback_read_char();
				}
				//if we have messages related to ps4link fio service
				else if(sockfd == request_socket) 
				{
					ps4sh_srv_read(request_socket);
				} 
				//if we have pending connection related to ps4sh server listener
				else if (sockfd == ps4sh_socket) 
				{
					clilen = sizeof(cliaddr);
					connfd = accept(ps4sh_socket, (struct sockaddr *)&cliaddr, &clilen);
					//search empty space
					for(j = 0; i<FD_SETSIZE; j++) 
					{
						if(client[j] < 0) 
						{
							client[j] = connfd;
							break;
						}
					}
					//populate in the set
					FD_SET(connfd, &master_set);
					//sanity checks
					if(connfd > maxfd) 
					{
						maxfd = connfd;
					}
					if ( j > maxi ) 
					{
						maxi = j;
					}
					if (--nready <= 0) 
					{
						continue;
					}
				} 
				else 
				{
					if ( ps4sh_srv_read(sockfd) < 0 ) {
						close(sockfd);
						FD_CLR(sockfd, &master_set);
						client[i] = -1;
						maxi--;
					}
				}
			}
		}
	}

	rl_callback_handler_remove();
	if ( (ret = network_disconnect(request_socket)) == -1 ) {
		debugNetPrintf(ERROR,"From request_socket network_disconect %s\n",strerror(errno));
	}
	if ( (ret = network_disconnect(console_socket)) == -1 ) {
		debugNetPrintf(ERROR,"From console_socket network_disconect %s\n",strerror(errno));		
	}
	if ( log_to_file ) {
		if ((ret = close(log_f_fd)) == -1)
			debugNetPrintf(ERROR,"From file log closing %s\n",strerror(errno));				
	}
    
    



	if (strcmp(ps4sh_history, "") != 0 ) {
		if ( (ret = write_history(ps4sh_history)) != 0) 
			debugNetPrintf(ERROR,"From ps4sh_history %s\n",strerror(errno));				
	}
	printf("\n");
	return(0);
		
}
コード例 #16
0
ファイル: shell.c プロジェクト: megabajt/poldek
int poclidek_shell(struct poclidek_ctx *cctx)
{
    const char *prompt_prefix = "poldek";
    char *line, *s, *home;

    if (cctx->htcnf) {
        tn_hash *global = poldek_conf_get_section(cctx->htcnf, "global");
        const char *s = global ? poldek_conf_get(global, "prompt", NULL) : NULL;
        if (s) {
            prompt_prefix = s;
            DBGF("prompt_prefix %s\n", s);
        }
        
    }
    
    if (!isatty(fileno(stdout))) {
        logn(LOGERR, _("not a tty"));
        return 0;
    }

    if (!init_shell(cctx))
        exit(EXIT_FAILURE);
    
    initialize_readline();
    histfile = NULL;

    if ((home = getenv("HOME"))) {
        int len = strlen(home) + strlen("/.poldek_history") + 2;
        histfile = alloca(len);
        snprintf(histfile, len, "%s/.poldek_history", home);
        read_history(histfile);
    }

    sigint_init();
    sigint_push(sigint_cb);
    signal(SIGTERM, shell_end);
    signal(SIGQUIT, shell_end);
    
    printf(_("\nWelcome to the poldek shell mode. "
             "Type \"help\" for help with commands.\n\n"));

    shDone = 0;
    while (!shDone) {
        struct pkg_dent *currdir = sh_ctx.cctx->currdir;
        char prompt[255];
        
        sigint_reset();
        n_snprintf(prompt, sizeof(prompt), "%s:%s%s> ", prompt_prefix,
                   currdir == NULL ? "/" : *currdir->name == '/' ? "" : "/",
                   currdir == NULL ? "" : currdir->name);

        if ((line = readline(prompt)) == NULL)
            break;

        /* add to history? */
        s = line;
        while (isspace(*s))
            s++;
        
        if (*s)
            add_history(line);
                
        s = n_str_strip_ws(line);
        if (*s) {
            shInCmd = 1;
            DBGF("(%s)\n", s);

            MEMINF("BEFORE %s\n", s);
            poclidek_execline(cctx, NULL, s);
            MEMINF("AFTER  %s\n", s);
            
            sigint_reset();
            shDone = 0;
            shInCmd = 0;
        }
        free(line);
        
        signal(SIGTERM, shell_end);
        signal(SIGQUIT, shell_end);

        if (shQuit)
            shDone = 1;
    }
    
    if (histfile) 
        write_history(histfile);
    
    sigint_pop();
    msg(0, "\n");
    return 1;
}
コード例 #17
0
ファイル: gretlcli.c プロジェクト: aylusltd/gretl
int main (int argc, char *argv[])
{
#ifdef WIN32
    char *callname = argv[0];
#endif
    char linecopy[MAXLINE];
    DATASET *dset = NULL;
    MODEL *model = NULL;
    ExecState state;
    char *line = NULL;
    int quiet = 0;
    int makepkg = 0;
    int load_datafile = 1;
    char filearg[MAXLEN];
    char runfile[MAXLEN];
    double scriptval = NADBL;
    CMD cmd;
    PRN *prn = NULL;
    PRN *cmdprn = NULL;
    int err = 0;

#ifdef G_OS_WIN32
    win32_set_gretldir(callname);
#endif

    nls_init();

#ifdef HAVE_READLINE
    rl_bind_key(0x18, ctrl_x);
#endif

    dset = datainfo_new();
    if (dset == NULL) {
	noalloc();
    }

    if (argc < 2) {
	load_datafile = 0;
    } else {
	gretlopt opt = 0;

	err = parse_options(&argc, &argv, &opt, &scriptval, filearg);

	if (!err && (opt & (OPT_DBOPEN | OPT_WEBDB))) {
	    /* catch GUI-only options */
	    err = E_BADOPT;
	}

	if (err) {
	    /* bad option */
	    usage(1);
	} else if (opt & (OPT_HELP | OPT_VERSION)) {
	    /* we'll exit in these cases */
	    if (opt & OPT_HELP) {
		usage(0);
	    } else {
		logo(0);
		exit(EXIT_SUCCESS);
	    }
	}
	    
	if (opt & (OPT_BATCH | OPT_RUNIT | OPT_MAKEPKG)) {
	    if (*filearg == '\0') {
		/* we're missing a filename argument */
		usage(1);
	    } else {
		/* record argument (not a datafile) */
		strcpy(runfile, filearg);
		load_datafile = 0;
		if (opt & OPT_BATCH) {
		    batch = 1;
		} else if (opt & OPT_MAKEPKG) {
		    batch = 1;
		    makepkg = 1;
		} else {
		    runit = 1;
		}
	    }
	} else if (*filearg == '\0') {
	    load_datafile = 0;
	}

	if (opt & OPT_QUIET) {
	    quiet = 1;
	}

	if (opt & OPT_ENGLISH) {
	    force_language(LANG_C);
	}
    }

    libgretl_init();

    logo(quiet);
    if (!quiet) {
	session_time(NULL);
    }

    prn = gretl_print_new(GRETL_PRINT_STDOUT, &err);
    if (err) {
	noalloc();
    }

    line = malloc(MAXLINE);
    if (line == NULL) {
	noalloc();
    }

#ifdef WIN32
    win32_cli_read_rc(callname);
#else
    cli_read_rc();
#endif /* WIN32 */

    if (!batch) {
	strcpy(cmdfile, gretl_workdir());
	strcat(cmdfile, "session.inp");
	cmdprn = gretl_print_new_with_filename(cmdfile, &err);
	if (err) {
	    errmsg(err, prn);
	    return EXIT_FAILURE;
	}
    }

    if (load_datafile) {
	handle_datafile(filearg, runfile, dset, prn, cmdprn);
    }

    /* allocate memory for model */
    model = allocate_working_model();
    if (model == NULL) {
	noalloc(); 
    }

    gretl_cmd_init(&cmd);
    gretl_exec_state_init(&state, 0, line, &cmd, model, prn);
    set_debug_read_func(get_interactive_line);

    /* print list of variables */
    if (data_status) {
	varlist(dset, prn);
    }

    if (!na(scriptval)) {
	/* define "scriptopt" */
	gretl_scalar_add("scriptopt", scriptval);
    }

    /* misc. interactive-mode setup */
    if (!batch) {
	check_help_file();
	fb = stdin;
	push_input_file(fb);
	if (!runit && !data_status) {
	    fputs(_("Type \"open filename\" to open a data set\n"), stdout);
	}
    }

#ifdef HAVE_READLINE
    initialize_readline();
#endif
    
    if (batch || runit) {
	/* re-initialize: will be incremented by "run" cmd */
	runit = 0;
	if (makepkg) {
	    set_gretl_echo(0);
	}
	if (strchr(runfile, ' ')) {
	    sprintf(line, "run \"%s\"", runfile);
	} else {
	    sprintf(line, "run %s", runfile);
	}
	err = cli_exec_line(&state, dset, cmdprn);
	if (err && fb == NULL) {
	    exit(EXIT_FAILURE);
	}
    }

    *linecopy = '\0';

    /* main command loop */
    while (cmd.ci != QUIT && fb != NULL && !xout) {
	if (err && gretl_error_is_fatal()) {
	    gretl_abort(linecopy);
	}

	if (gretl_execute_loop()) { 
	    if (gretl_loop_exec(&state, dset, NULL)) {
		return 1;
	    }
	} else {
	    err = cli_get_input_line(&state);
	    if (err) {
		errmsg(err, prn);
		break;
	    }
	}

	if (!state.in_comment) {
	    if (cmd.context == FOREIGN || cmd.context == MPI ||
		gretl_compiling_python(line)) {
		tailstrip(line);
	    } else {
		err = maybe_get_input_line_continuation(line); 
		if (err) {
		    errmsg(err, prn);
		    break;
		}
	    }
	} 

	strcpy(linecopy, line);
	tailstrip(linecopy);
	err = cli_exec_line(&state, dset, cmdprn);
    } /* end of get commands loop */

    if (!err) {
	err = gretl_if_state_check(0);
	if (err) {
	    errmsg(err, prn);
	}
    }

    if (makepkg && !err) {
	switch_ext(filearg, runfile, "gfn");
	sprintf(line, "makepkg %s\n", filearg);
	cli_exec_line(&state, dset, cmdprn);
    }

    /* leak check -- try explicitly freeing all memory allocated */

    destroy_working_model(model);
    destroy_dataset(dset);

    if (fb != stdin && fb != NULL) {
	fclose(fb);
    }

    free(line);

    gretl_print_destroy(prn);
    gretl_cmd_free(&cmd);
    libgretl_cleanup();

    return 0;
}
コード例 #18
0
ファイル: npsh.c プロジェクト: AzagraMac/PS2_SDK
int
main(int argc, char* argv[])
{
    int ret, i;
    struct timeval time, start, last;
    fd_set rset, mset;
    VERBOSE = 0;
    printf("npsh v1.0\n");
    read_config();

    fcntl(0, F_SETFL, O_NONBLOCK);
    FD_ZERO(&mset);
    FD_SET(0, &mset);
    initialize_readline();
    if ( initialize_naplink() != 0 ) {
        rl_callback_handler_remove();
        return(1);
    }
    np_set_counter(0);
    naplink_check();
    naplink_process();
    gettimeofday(&start, NULL);
    while(doloop)
    {
        time.tv_sec = 0;
        time.tv_usec = 100;
        rset = mset;
        if ( !timedout ) {
            naplink_check();
            naplink_process();
            np_set_processing(0);
        }
        ret = select(0+1, &rset, NULL, NULL, &time);
        if ( ret < 0 )
        {
            perror("select");
        } else if (ret == 0) {
        } else {
            if ( timedout ) {
                printf("we timedout lets reinit\n");
                initialize_naplink();
                np_set_counter(0);
                naplink_check();
                naplink_process();
                timedout = 0;
                np_set_processing(0);
            }

            if (FD_ISSET(0, &rset))
            {
                rl_callback_read_char();
            }
        }
        if ( !timedout ) {
            for (i = 0; i < 10; i++)
            {
                naplink_process();
            }
        }
        if ( timeout > 0 ) {
            if (np_get_counter() > timeout) {
                naplink_close();
                np_set_counter(0);
                timedout = 1;
            }
        }
    }

    naplink_close();
    
    rl_callback_handler_remove();
    if ( log_to_file )
        if ((ret = close(log_f_fd)) == -1)
            perror("log_f_fd");
    if (strcmp(pksh_history, "") != 0 ) {
        if ( (ret = write_history(pksh_history)) != 0) 
            perror("write_history");
    }
    return(0);
}