Example #1
0
int main(void)
{
	char command[MAX_LINE];
	char *args[MAX_LINE/2+1];
	int should_run = 1;
	int top = 0;
	char stack[MAX_COMMAND][MAX_LINE];

	signal(SIGCHLD, handler);

	while (should_run)
	{
		print_prompt();
		fflush(stdout);
		if (fgets(command, MAX_LINE, stdin)==NULL)
		{
			perror("fgets");
			return 1;
		}
		command[strlen(command)-1] = '\0';
		if (strlen(command)==0) continue;
		else if (strcmp(command, "exit")==0) should_run = 0;
		else if (strcmp(command, "history")==0)
		{
			int i;
			for (i=0; i<10 && i<top; ++i)
				printf("\t%d %s\n", top-i, stack[top-i]);
		}
		else{
			if (strcmp(command, "!!")==0)
			{
				if (top) strcpy(command, stack[top]);
				else{
					printf("No commands in history.\n");
					continue;
				}
			}
			else if (command[0]=='!')
			{
				int index = atoi(command+1);
				if (0<index && index<=top) strcpy(command, stack[index]);
				else{
					printf("No such command in history.\n");
					continue;
				}
			}
			strcpy(stack[++top], command);
			int background = splitCommand(command, args);
			if (strcmp(args[0], "cd")==0)
			{
				int ret = chdir(args[1]);
				if (ret==-1) perror("cd");
				continue;
			}
			pid_t pid = fork();
			if (!pid)
			{
				int p1 = 0, p2 = 0, p3 = 0, i = 0;
				while (args[++i]!=NULL)
					if (strcmp(args[i], "<")==0) p1 = i;
					else if (strcmp(args[i], ">")==0) p2 = i;
					else if (strcmp(args[i], ">>")==0) p3 = i;

				if (p1) freopen(args[p1+1], "r", stdin);
				if (p2) freopen(args[p2+1], "w", stdout);
				if (p3) freopen(args[p3+1], "a", stdout);
				if (p1) args[p1] = NULL;
				if (p2) args[p2] = NULL;
				if (p3) args[p3] = NULL;

				int ret = execvp(args[0], args);
				if (ret==-1)
				{
					perror("execvp");
					return 1;
				}
			}
			if (!background) wait(NULL);
		}
	}
	
	return 0;
}
Example #2
0
void terminal_command_return_callback(uckernel_task_event event, uckernel_task_data data)
{
	serio_set_rx_handler(terminal_receive_handler);
	print_prompt();
}
Example #3
0
/*-------------------------------------------------------------------------*/
int
tls_continue_handshake (interactive_t *ip)

/* Continue the TLS initialisation handshake for interactive <ip>.
 * Return a negative error code if the connection can not be set up.
 * Return 0 if the connection is still begin set up.
 * Return 1 if the connection is now active (or if no secure connection
 * had been requested).
 *
 * If a callback is set for <ip> and connection comes out of the handshaking
 * state, it will be called with the result code.
 */

{
    int ret;

    if (ip->tls_status != TLS_HANDSHAKING)
        return 1;

    ret = tls_do_handshake(ip);
    if (!ret)
	return 0;


    if (ret < 0)
    {
        ip->tls_status = TLS_INACTIVE;
    }
    else
    {
        ip->tls_status = TLS_ACTIVE;
    }

    /* If the connection is no longer in handshake, execute the callback */
    if (ip->tls_cb != NULL)
    {
        tls_cb_handler_t * handler;

        xallocate( handler, sizeof(*handler)
                 , "TLS: Callback handler protector");
        handler->cb = ip->tls_cb;
        ip->tls_cb = NULL;
            /* Protect the callback during its execution. */

        push_error_handler (handle_tls_cb_error, &(handler->head));

        push_number(inter_sp, ret < 0 ? ret : 0);
        push_ref_object(inter_sp, ip->ob, "tls_handshake");

        command_giver = ip->ob;
        current_interactive = ip->ob;
        /* Set current_interactive as it would be for a normal logon() call. */

        (void)apply_callback(handler->cb, 2);

        if (!(ip->ob->flags & O_DESTRUCTED))
            print_prompt();

        command_giver = NULL;

        free_svalue(inter_sp); inter_sp--; /* free the callback */
    }

    return ret;
} /* tls_continue_handshake() */
Example #4
0
int ss_listen (int sci_idx)
{
    char *cp;
    ss_data *info;
    sigret_t (*sig_int)(int), (*old_sig_cont)(int);
    char input[BUFSIZ];
    sigset_t omask, igmask;
    int code;
    jmp_buf old_jmpb;
    ss_data *old_info = current_info;
    char *line;
    
    current_info = info = ss_info(sci_idx);
    sig_cont = (sigret_t (*)(int)) 0;
    info->abort = 0;
    sigemptyset(&igmask);
    sigaddset(&igmask, SIGINT);
    sigprocmask(SIG_BLOCK, &igmask, &omask);
    memcpy(old_jmpb, listen_jmpb, sizeof(jmp_buf));
    sig_int = signal(SIGINT, listen_int_handler);
    setjmp(listen_jmpb);
    sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);

    while(!info->abort) {
	old_sig_cont = sig_cont;
	sig_cont = signal(SIGCONT, print_prompt);
	if (sig_cont == print_prompt)
	    sig_cont = old_sig_cont;
	if (info->readline) {
		line = (*info->readline)(current_info->prompt);
	} else {
		print_prompt(0);
		if (fgets(input, BUFSIZ, stdin) == input)
			line = input;
		else
			line = NULL;
	
		input[BUFSIZ-1] = 0;
	}
	if (line == NULL) {
		code = SS_ET_EOF;
		(void) signal(SIGCONT, sig_cont);
		goto egress;
	}
		
	cp = strchr(line, '\n');
	if (cp) {
	    *cp = '\0';
	    if (cp == line)
		continue;
	}
	(void) signal(SIGCONT, sig_cont);
	if (info->add_history)
		(*info->add_history)(line);

	code = ss_execute_line (sci_idx, line);
	if (code == SS_ET_COMMAND_NOT_FOUND) {
	    register char *c = line;
	    while (*c == ' ' || *c == '\t')
		c++;
	    cp = strchr (c, ' ');
	    if (cp)
		*cp = '\0';
	    cp = strchr (c, '\t');
	    if (cp)
		*cp = '\0';
	    ss_error (sci_idx, 0,
		    "Unknown request \"%s\".  Type \"?\" for a request list.",
		       c);
	}
	if (info->readline)
		free(line);
    }
    code = 0;
egress:
    (void) signal(SIGINT, sig_int);
    memcpy(listen_jmpb, old_jmpb, sizeof(jmp_buf));
    current_info = old_info;
    return code;
}
Example #5
0
/**
 * Process the user input
 * It handles building commands to the server as well as just sending messages
 */
int process_user(){
	int buffer_len = strlen(buffer);
	int command = 0;
	unsigned char* next_arg = buffer;

	print_prompt(windows[INPUT_WIN]);

	if(buffer_len == 0){
		return 0;
	}

	// TODO: add command processing
	if(buffer[0] == '/'){
		next_arg = strchr(buffer,' ');
		if(next_arg){
			*next_arg = 0; // null terminate the command
			next_arg++;
		}

		if(strcmp(buffer+1,"who") == 0){
			command = USER_LIST;
		}
		else if(strcmp(buffer+1,"pm") == 0){
			command = PM;
		}
		else if(strcmp(buffer+1,"whois") == 0){
			command = WHOIS;
		}
		else if(strcmp(buffer+1,"q") == 0){
			command = -1;
		}
		else if(strcmp(buffer+1,"quit") == 0){
			command = -1;
		}
		else if(strcmp(buffer+1,"help") == 0){
			command = HELP;
		}
	}

	switch(command){
		case -1:
			close_interface();
			return -1;
		break;
		case 0:
		{
			struct message message;
			memset(&message,0,sizeof(struct message));
			strcpy(message.message,buffer);

			message.length = strlen(message.message);
			message.user_id = CONFIG->self.id;
			send_message(CONFIG->self.socket,&message);
		}
		break;
		case PM:
		{
			unsigned char* to = next_arg;
			next_arg = strchr(next_arg,' ');
			if(next_arg){
				*next_arg = 0; // null terminate the command
				next_arg++;
			}else{
				return 0;
			}

			struct private_message message;
			memset(&message,0,sizeof(struct private_message));
			strcpy(message.to, to);
			strcpy(message.message.message,next_arg);

			message.message.length = strlen(message.message.message);
			message.message.user_id = CONFIG->self.id;
			message.from = CONFIG->self.id;
			send_pm(CONFIG->self.socket,&message);
		}
		break;
		case WHOIS:
		{
			send_whois_request(CONFIG->self.socket, next_arg);
		}
		break;
		case USER_LIST:
			send_user_list_request(CONFIG->self.socket);
		break;
		case HELP:
		{
			struct message msg;
			msg.user_id = 65535;
			memset(msg.message,0,sizeof(msg.message));
			strcpy(msg.message,"[Commands: ]");
			msg.length = strlen(msg.message);
			add_message(&msg);
			strcpy(msg.message,"[who	Show who is on the server]");
			msg.length = strlen(msg.message);
			add_message(&msg);
			strcpy(msg.message,"[whois <user> <msg>	Get details about a user]");
			msg.length = strlen(msg.message);
			add_message(&msg);
			strcpy(msg.message,"[pm <username>	Send a private message to a user]");
			msg.length = strlen(msg.message);
			add_message(&msg);
			/*strcpy(msg.message,"[Commands: ]");
			msg.length = strlen(msg.message);
			add_message(&msg);
			strcpy(msg.message,"[Commands: ]");
			msg.length = strlen(msg.message);
			add_message(&msg);
			*/
			show_messages(windows[CHAT_WIN]);
			wrefresh(windows[CHAT_WIN]);
		}
		break;
	}

	memset(buffer,0,sizeof(buffer));
	return 0;
}
Example #6
0
int main(int argc,char *argv[])
{
    int
	rc;

    char
	*k,
	*v,
	*line,
	buf[BUFSIZ];

    ght_hash_table_t
	*p_table=NULL;

    /* create hash table of size 256 */
    p_table=ght_create(256);
    if (p_table == NULL)
    {
	print_it("Error: Could not create hash table\n");
	return(1);
    }

    print_menu();
    for (;;)
    {
	print_prompt();


	line=fgets(buf,sizeof(buf)-1,stdin);
	if (line == NULL)
	    break;

	switch(*line)
	{
	    case 'i':
	    {
		k=read_data("Enter key: ");
		v=read_data("Enter value: ");
		if (k && v)
		{
		    /* insert to hash table */
		    rc=ght_insert(p_table,
			    v,
			    strlen(k),
			    k);
		    if (rc == 0)
		    {
			print_it("Inserted: Key=%s, Value=%s\n",
				k,v);
			free(k);
		    }
		    else
		    {
			print_it("Error: ght_insert() failed\n");
			(void) free((char *) k);
			(void) free((char *) v);
		    }
		}
		else
		{
		    if (k)
			(void) free((char *) k);
		    if (v)
			(void) free((char *) v);

		}

		break;
	    }

	    case 'r': /* replace */
	    {
		k=read_data("Enter key: ");
		v=read_data("Enter new value: ");
		if (k && v)
		{
		    char *
			 old_val;
		    /* Replace a key in the hash table */
		    old_val = (char*)ght_replace(p_table,
						 v,
						 strlen(k),
						 k);
		    if (old_val != NULL)
		    {
			print_it("Replaced: Key=%s, Old Value=%s, Value=%s\n",
				k,old_val, v);
			free(old_val);
			free(k);
		    }
		    else
		    {
			print_it("Error: ght_replace() failed\n");
			(void) free((char *) k);
			(void) free((char *) v);
		    }
		}
		else
		{
		    if (k)
			(void) free((char *) k);
		    if (v)
			(void) free((char *) v);

		}
		break;
	    }

	    case 'h':
	    {
		print_menu();
		break;
	    }

	    case 'n': /* number of elements */
	    {
		print_it("Number elements in hash table: %d\n",
			ght_size(p_table));
		break;
	    }

	    case 's': /* size of hash table */
	    {
		print_it("Hash table size: %d\n",
			ght_table_size(p_table));

		break;
	    }

	    case 't': /* dump */
	    {
		const void
		    *pk,
		    *pv;

		ght_iterator_t
		    iterator;

		for (pv=(char *) ght_first(p_table,&iterator, &pk);
		     pv;
		     pv=(char *) ght_next(p_table,&iterator, &pk))
		{
		    print_it("%s => %s\n",(char *) pk,(char *) pv);
		}
		break;
	    }

	    case 'd':
	    {
		k=read_data("Enter key to delete: ");
		if (k)
		{
		    v=ght_remove(p_table,
			    strlen(k),
			    k);
		    if (v)
		    {
			print_it("Removed %s => %s",k,v);
			(void) free((char *) v);
		    }
		    else
		    {
			print_it("Error: could not find data for key %s\n",
				k);
		    }
		    (void) free((char *) k);
		}

		break;
	    }

	    case 'l':
	    {
		k=read_data("Enter key: ");
		if (k)
		{
		    v=(char *) ght_get(p_table,strlen(k),k);
		    if (v)
		    {
			print_it("Found: %s => %s\n",k,v);
		    }
		    else
		    {
			print_it("No data found for key: %s\n",k);
		    }
		    (void) free((char *) k);

		}
		break;
	    }

	    case 'q':
	    {
		if (p_table)
		{
		    const void
			*pv,
			*pk;

		    ght_iterator_t
			iterator;

		    for (pv=(char *) ght_first(p_table,&iterator, &pk);
			 pv;
			 pv=(char *) ght_next(p_table,&iterator, &pk))
		    {
			(void) free((char *) pv);
		    }
		    ght_finalize(p_table);
		}

		return(0);
		break;
	    }

	    default:
	    {
		print_it("Unknown option\n");
		break;
	    }
	}
    }
    return(0);
}
void microrl_print_prompt (microrl_t * pThis)
{
	print_prompt(pThis);
}
Example #8
0
int main(void) {
    unsigned program_args_size = 0;
    unsigned num_program_args = 0;
    char *** program_args = (char ***) new_array(&program_args_size);
    char * file_in = NULL;
    char * file_out = NULL;

    Result parse_result;
    Result exec_result;
    while (1) {
        print_prompt();

        /* Parse the current line. */
        parse_result = parse(&program_args, &num_program_args, &program_args_size,
                             &file_in, &file_out);

        /* Do nothing on empty commands (loop around). */
        if (parse_result == Empty) {
            continue;
        }
        /* Break from the loop on Ctrl-D or 'exit'. */
        else if (parse_result == Exit) {
            break;
        }
        /* In the case of an error, free the successfuly parsed arguments and continue. */
        else if (parse_result == Error) {
            free_iteration_data();
            continue;
        }

        #ifdef DEBUG
        printf("Parsed Program Arguments:\n");
        unsigned i;
        for (i = 0; i < num_program_args; i++) {
            printf("> ");
            for (unsigned j = 0; program_args[i][j] != NULL; j++) {
                printf("%s ", program_args[i][j]);
            }
            printf("\n");
        }
        fflush(stdout);
        #endif

        /* Execute the command. */
        exec_result = execute(program_args, file_in, file_out, num_program_args);

        /* Free the program argument vectors and their contents, but retain the capacity of
         * program_args.
         */
        free_iteration_data();

        /* If the exec failed fatally, allow the child to exit. */
        if (exec_result == Exit) {
            break;
        }
    }

    free(program_args);
    flex_cleanup();

    return 0;
}
Example #9
0
int main(int argc, const char* argv[])
{
    int status, bg_pipes[2], num_pipes, flags;
    struct sigaction act_bg_term, act_int_old, act_int_new;
    /* Define handler for SIGINT (ignore) */
    act_int_new.sa_handler = SIG_IGN;
    act_int_new.sa_flags = 0;
    if (sigaction(SIGINT, &act_int_new, &act_int_old))
        perror("Failed to change handler for SIGINT");

    /* Define handler for detecting background process termination */
    if (SIGNAL_DETECTION == 1)
    {
        if (sigaction(SIGUSR1, NULL, &act_bg_term))
            perror("Failed to get handler for SIGUSR1");
        act_bg_term.sa_handler = sig_bg_handler;
        act_bg_term.sa_flags = SA_RESTART;
        if (sigaction(SIGUSR1, &act_bg_term, NULL))
            perror("Failed to set handler for SIGUSR1");
    }

    /* Create pipe for printing background process info */
    num_pipes = 1;
    create_pipes(bg_pipes, num_pipes);

    /* Configure pipe to be non-blocking on read end */
    flags = fcntl(bg_pipes[0], F_GETFL, 0);
    fcntl(bg_pipes[0], F_SETFL, flags | O_NONBLOCK);

    while (1)
    {
        char input[80], cmd[80];
        int i;

        /* Wait for all defunct children */
        /* Continue even if no child has exited */
        if (!(SIGNAL_DETECTION == 1))
            while (waitpid(-1, &status, WNOHANG | WUNTRACED) > 0);

        /* Print prompt */
        if (!print_prompt()) continue;

        /* Exit if error occurs */
        if (!fgets(input, 80, stdin))
        {
            perror("Failed to get input");
            continue;
        }

        /* Remove newline, if present */
        i = strlen(input) - 1;
        if (input[i] == '\n') input[i] = '\0';

        /* Read given commands */
        i = 0; /* Input index */
        i = read_cmd(cmd, input, i);

        if (strcmp(cmd, "exit") == 0)
            break;
        else if (strcmp(cmd, "cd") == 0)
            cd(input, cmd, i);
        else if (strcmp(cmd, "checkEnv") == 0)
            check_env(input, i);
        else if (cmd[0] == '\0') {} /* Just print process info */
        else
            general_cmd(input, &act_int_old, bg_pipes);

        /* Print accumulated process information */
        print_process_info(bg_pipes);
    }

    /* Close pipe for printing background process info */
    close_pipes(bg_pipes, num_pipes);

    exit_shell();

    return 0;
}
Example #10
0
void handle_signal(int sig_num)
{
    printf("\n");
    print_prompt();
    fflush(stdout);
}
Example #11
0
int main(int argc, char **argv)
{
    signal(SIGINT, handle_signal);

    char line[MAXLINE]; /* The current input line */

    /* Points to the beginning of the list of current command tokens */
    cmd_tok *current_cmd = NULL;

    /* Points to a token within the command tokens list */
    cmd_tok *current_tok_ptr = NULL;

    print_prompt();
    int length = 0;
    while((length = getln(line, MAXLINE)) > 0)
    {
        if (length == 1 && line[0] == '\n')
        {
            /* They pushed enter without any text */
            print_prompt();
            continue;
        }
        char *token = strtok(line, " ");
        current_cmd = create_cmd_tok(token);
        current_tok_ptr = current_cmd;
        token = strtok(NULL, " ");

        /* Continue to tokenize input line */
        while (token != NULL)
        {
            current_tok_ptr->next_token = create_cmd_tok(token);
            current_tok_ptr = current_tok_ptr->next_token;
            token = strtok(NULL, " ");
        }

        /* Process the command */

        /* Check if it was one of the internal commands: exit, cd */
        if (strcmp(current_cmd->current_token, "exit") == 0)
        {
            destroy_cmd_toks(current_cmd);
            return 0;
        }
        else if (strcmp(current_cmd->current_token, "cd") == 0)
        {
            char *directory = NULL;
            int num_args = get_num_tokens(current_cmd);
            if (num_args == 1)
            {
                /* The user just typed "cd".  Go to home directory. */
                directory = getenv("HOME");
            }
            else
            {
                /* Get the token after "cd" */
                directory = current_cmd->next_token->current_token;
            }

            int cd_return_val = chdir(directory);

            /* chdir returns 0 if successful */
            if (cd_return_val != 0)
            {
                /* Print error messages */
                char *error_msg =
                    (char *)malloc(sizeof(argv[0]) +
                                   sizeof(directory) + 7*sizeof(char));
                strcpy(error_msg, argv[0]);
                strcat(error_msg, ": cd: ");
                strcat(error_msg, directory);
                perror(error_msg);
                free(error_msg);
            }
        }
        else
        {
            /* Assume input was an external executable command */
            char **args = create_args(current_cmd);

            /* In case executable is not on path, allocate memory for
               args[0] with ./ prepended */
            char *arg0 = NULL;
            int child_pid = fork();
            if (child_pid == 0)
            {
                execvp(args[0], args);

                /* execvp only returns if it fails */

                /* Didn't find command on path,
                try looking in current directory */
                arg0 = (char *)malloc(sizeof(args[0]) + 3*sizeof(char));
                strcpy(arg0, "./");
                strcat(arg0, args[0]);
                execvp(arg0, args);

                /* Couldn't find command */
                print_cmd_not_found(args[0]);
                return 0;
            }
            else
            {
                signal(SIGINT, child_terminate_handler);
                wait(NULL);
            }
            signal(SIGINT, handle_signal);
            free(args);
            free(arg0);
        }

        /* Free and reset command pointers */
        destroy_cmd_toks(current_cmd);
        current_cmd = NULL;
        current_tok_ptr = NULL;

        print_prompt();
    }

    /* In case they exit with control-D,
       want prompt to show up on new line */
    printf("\n");

    return 0;
}
Example #12
0
//}
int main(int argc, char **argv)
{
	user_chat_box_t use;
	strcpy(use.name, argv[1]);
	/* Extract pipe descriptors and name from argv */
	//converting pipe file descriptors back to integers
	int rd = atoi(argv[2]);
	int wr = atoi(argv[3]);
	//int rd = (int) strtol(argv[2], (char **)NULL, 10);
	//int wr = (int) strtol(argv[3], (char **)NULL, 10);
	//printf("rd %d    wr %d\n", rd, wr);
	//forking a child process to write commands to server
	use.child_pid = fork();

	if (use.child_pid == -1)
	{
		exit(-1);
	}
	//Child process writes commands to write end of pipe
	else if (use.child_pid == 0)
	{
		//closing write end of pipe
		close(wr);
		char line[MSG_SIZE];
		fcntl(rd, F_SETFL, O_NONBLOCK);
		int nread;
		while(1)
		{
			nread = read(rd, line, MSG_SIZE);
			//printf("%d\n", nread);
			usleep(1000);
			if (nread > 0)
			{
				//printf("%d\n", nread);
				printf("%s\n", line);
				print_prompt(use.name);
			}
		}

		
	}
	//Parent process checks if there is anything was written from the server available to read.
	else
	{
		//closing read end of pipe
		close(rd);
		char l[50];
		char *line;
		char chpd[50] = "\\child_pid \0";
		int nwrite;
		//writing child_pid command in order to feed the child_pid back to server
		sprintf(l, "%d", getpid());
		strcat(chpd, l);
		write(wr, chpd, MSG_SIZE);
		print_prompt(use.name);
		while(1)
		{
			usleep(1000);
			line = sh_read_line();
			if (strlen(line) > 0)
			{
				if (sh_handle_input(line) == 1)
				{
					nwrite = write(wr, line, MSG_SIZE);
					if (nwrite < 0)
					{
						printf("*** ERROR: Failed to write to pipe\n");
            exit(1);
					}
					//close(wr);
				}
				else print_prompt(use.name);
				line[0] = '\0';
			}
		}	
	}
}
Example #13
0
void do_INTERPRET(interpret_decision_t *decision)
{
#define SIGNAL_NOP()       do { decision->id_status = INTERPRET_NOP;          return; } while(0)
#define SIGNAL_EMPTY()     do { decision->id_status = INTERPRET_EMPTY;        return; } while(0)
#define SIGNAL_EXEC_WORD() do { decision->id_status = INTERPRET_EXECUTE_WORD; return; } while(0)
#define SIGNAL_EXEC_LIT()  do { decision->id_status = INTERPRET_EXECUTE_LIT;  return; } while(0)
#define SIGNAL_EXEC_2LIT() do { decision->id_status = INTERPRET_EXECUTE_2LIT; return; } while(0)

  counted_string_t *wb = __read_word(' ');

  if (!wb->cs_len) {
    print_prompt(var_SHOW_PROMPT);
    __refill_input_buffer();

    SIGNAL_EMPTY();
  }

  word_header_t *word;
  int found = fw_search(wb, &word);

  if (found) {
    cf_t *cfa = fw_code_field(word);

    if (IS_INTERPRET() || word->wh_flags & F_IMMED) {
      decision->u.id_cfa = cfa;
      SIGNAL_EXEC_WORD();
    }

    COMPILE(cfa);
    SIGNAL_NOP();
  }

  parse_number_result_t pnr;
  int ret = parse_number(wb, &pnr);

  if (ret == -1 || pnr.nr_remaining != 0) {
    __ERR_undefined_word();

    var_STATE = STATE_INTERPRET;
    __refill_input_buffer();
    SIGNAL_NOP();
  }

  if (ret == 0) {
    if (IS_INTERPRET()) {
      decision->u.id_number = pnr.nr_number_lo;
      SIGNAL_EXEC_LIT();
    }

#if (CONFIG_PEEPHOLE == 1)
    switch(pnr.nr_number_lo) {
      case 0:
        COMPILE(&SI_LIT_0);
        break;
      case 1:
        COMPILE(&SI_LIT_1);
        break;
      case 2:
        COMPILE(&SI_LIT_2);
        break;
      case 0xFFFFFFFF:
        COMPILE(&SI_LIT_FFFFFFFF);
        break;
      default:
        COMPILE(&LIT);
        COMPILE(pnr.nr_number_lo);
        break;
    }
#else
    COMPILE(&LIT);
    COMPILE(pnr.nr_number_lo);
#endif
  } else {
    if (IS_INTERPRET()) {
      decision->u.id_double_number[0] = pnr.nr_number_lo;
      decision->u.id_double_number[1] = pnr.nr_number_hi;
      SIGNAL_EXEC_2LIT();
    }

    COMPILE((u32_t)&TWOLIT);
    COMPILE(pnr.nr_number_lo);
    COMPILE(pnr.nr_number_hi);
  }

  SIGNAL_NOP();
}
Example #14
0
/* main - Start of shell, doesn't care for arguments */
int main(int argc, char* argv[])
{
    int retval;

    char cmd_line[MAX_LENGTH];
    /* Allocate memory for argument vector */
    char **args = (char **) malloc(MAX_ARGS * sizeof(char*));

    /* Register proper signals to handle */
    register_signals();

    /* Set string for promt */
    USER = getenv("USER");

    /* Main loop */
    while (1)
    {

#ifndef SIGNALDETECTION
        /* Check if any background processes has exited */
        retval = check_background_procs();
        if (retval == -1 && errno != ECHILD)
            perror("wait failed");
#endif

        /* Print a new promt */
        print_prompt();

        /* Fetch new command from terminal */
        if (fgets(cmd_line, MAX_LENGTH, stdin) != NULL) /* Success */
        {
            /* Parse user command */
            retval = parse_command(cmd_line, args);

            if (retval == 1) /* Empty cmd */
                continue; /* Restart loop, for checking background etc.. */

            /* If the command is available as a builtin, use that */
            if (builtin(args))
            {
                retval = run_builtin(args);
                if (retval == B_EXIT) /* EXIT */
                {
                    retval = check_background_procs();
                    /* retval == 0 means no error for having no children were
                     * returned */

                    /* Kill all child processes */
                    if (retval == 0)
                        retval = kill(-getpid(), SIGKILL);

                    break; /* Breaks main loop and exits */
                }
                else if (retval == B_FALIURE) /* Something went wrong */
                    fprintf(stderr, "Command, %s, could not be executed\n", args[0]);
            }
            else /* Run a command */
            {
                /* Run in the background */
                if (background(args))
                {
                    run_program(args, 1);
                }
                else /* Run blocking */
                {
                    retval = run_program_block(args);
                    if (retval IS_ERROR)
                    {
                        if (retval == INVALIDARGS)
                            fprintf(stderr, "Invalid argument\n");
                        else if (retval == PIPEERROR)
                            fprintf(stderr, "Pipe error\n");
                        else if (retval == FORKERROR)
                            fprintf(stderr, "Fork error\n");
                    }
                }
            }
        }
    }

    /* Free memmory */
    free(args);
    
    return 0;
}
Example #15
0
void microrl_insert_char (microrl_t * pThis, int ch)
{
#ifdef _USE_ESC_SEQ
	if (pThis->escape) {
		if (escape_process(pThis, ch))
			pThis->escape = 0;
	} else {
#endif
		switch (ch) {
			//-----------------------------------------------------
#ifdef _ENDL_CR
			case KEY_CR:
				new_line_handler(pThis);
			break;
			case KEY_LF:
			break;
#elif defined(_ENDL_CRLF)
			case KEY_CR:
				pThis->tmpch = KEY_CR;
			break;
			case KEY_LF:
			if (pThis->tmpch == KEY_CR)
				new_line_handler(pThis);
			break;
#elif defined(_ENDL_LFCR)
			case KEY_LF:
				pThis->tmpch = KEY_LF;
			break;
			case KEY_CR:
			if (pThis->tmpch == KEY_LF)
				new_line_handler(pThis);
			break;
#else
			case KEY_CR:
			break;
			case KEY_LF:
				new_line_handler(pThis);
			break;
#endif
			//-----------------------------------------------------
#ifdef _USE_COMPLETE
			case KEY_HT:
				microrl_get_complite (pThis);
			break;
#endif
			//-----------------------------------------------------
			case KEY_ESC:
#ifdef _USE_ESC_SEQ
				pThis->escape = 1;
#endif
			break;
			//-----------------------------------------------------
			case KEY_NAK: // ^U
					while (pThis->cursor > 0) {
					microrl_backspace (pThis);
				}
				terminal_print_line (pThis, 0, pThis->cursor);
			break;
			//-----------------------------------------------------
			case KEY_VT:  // ^K
				pThis->print ("\033[K");
				pThis->cmdlen = pThis->cursor;
			break;
			//-----------------------------------------------------
			case KEY_ENQ: // ^E
				terminal_move_cursor (pThis, pThis->cmdlen-pThis->cursor);
				pThis->cursor = pThis->cmdlen;
			break;
			//-----------------------------------------------------
			case KEY_SOH: // ^A
				terminal_reset_cursor (pThis);
				pThis->cursor = 0;
			break;
			//-----------------------------------------------------
			case KEY_ACK: // ^F
			if (pThis->cursor < pThis->cmdlen) {
				terminal_move_cursor (pThis, 1);
				pThis->cursor++;
			}
			break;
			//-----------------------------------------------------
			case KEY_STX: // ^B
			if (pThis->cursor) {
				terminal_move_cursor (pThis, -1);
				pThis->cursor--;
			}
			break;
			//-----------------------------------------------------
			case KEY_DLE: //^P
#ifdef _USE_HISTORY
			hist_search (pThis, _HIST_UP);
#endif
			break;
			//-----------------------------------------------------
			case KEY_SO: //^N
#ifdef _USE_HISTORY
			hist_search (pThis, _HIST_DOWN);
#endif
			break;
			//-----------------------------------------------------
			case KEY_DEL: // Backspace
			case KEY_BS: // ^U
				microrl_backspace (pThis);
				terminal_print_line (pThis, pThis->cursor, pThis->cursor);
			break;
			//-----------------------------------------------------
			case KEY_DC2: // ^R
				terminal_newline (pThis);
				print_prompt (pThis);
				terminal_reset_cursor (pThis);
				terminal_print_line (pThis, 0, pThis->cursor);
			break;
			//-----------------------------------------------------
#ifdef _USE_CTLR_C
			case KEY_ETX:
			if (pThis->sigint != NULL)
				pThis->sigint();
			break;
#endif
			//-----------------------------------------------------
			default:
			if (((ch == ' ') && (pThis->cmdlen == 0)) || IS_CONTROL_CHAR(ch))
				break;
			if (microrl_insert_text (pThis, (char*)&ch, 1))
				terminal_print_line (pThis, pThis->cursor-1, pThis->cursor);
			
			break;
		}
#ifdef _USE_ESC_SEQ
	}
#endif
}
Example #16
0
////
// main
//
//   The main function to the shell program.
//
int main (int argc, char **argv) {
   (void) argc;
   
   // variables
   set_execname (argv[0]);
   
   // loop until user exits
   while (TRUE) {   // repeat until user exits the shell
      char cmdline[1025]; // will only accept 1024
      bzero (cmdline, 1025);
      char parsebuffer[2024];
      bzero (parsebuffer, 2024);
      char *tokens[512];
      int toknum = 0;
//      bool pipein = FALSE;
//      bool pipeout = FALSE;
      
      print_prompt();    // print the prompt
      // get up to 1024 chars from the user
      if (get_cmdline (cmdline) == FALSE) continue;
      // break the line into tokens
      if (parseline (cmdline, parsebuffer, tokens, &toknum)) {
         // parseline returned an error
         eprintf ("%s: %s\n", "Error",
                  "parsing error caused by incorrect usage");
         continue;
      }

      // Check if the user wishes to exit the shell
      if (check_exit (tokens, toknum)) exit (get_exitstatus());
      

      // set the number of commands to be executed
      int numcmds = set_numofcmds (tokens, toknum);
      // the number of commands should not exceed 20
      if (numcmds > 20) {
         eprintf ("%s: %s\n", "ERROR", "cannot handle more than 20 commands");
         continue;
      }

      // initialize the current start index of the tokens
      int curstart;
      int nextstart = 0;
      
      int fd[2];
//      int fdin[2];
//      int fdout[2];
      // loop fork-exec for each command
      int i;
      for (i = 0; i < numcmds && nextstart < toknum; ++i) {
         // setup current command, update current start, and determine pipe
         curstart = nextstart;
         char *command = set_command (tokens, toknum, &nextstart);
         // a null command will cause an error
         if (command == NULL || command[0] == '\0') {
            eprintf ("%s: %s\n", "FATAL ERROR", "encountered a null command");
            break;
         }
         // make a new argv
         int newargc = get_newargc (tokens, curstart, nextstart);
         char *newargv[newargc + 1];
         newargv[0] = command;
         newargv[newargc] = NULL;
         int j = 1;
         int k;
         for (k = curstart; k < nextstart && j < newargc; ++k) {
            if (tokens[k][0] == '1') {
               newargv[j] = &tokens[k][1];
               ++j;
            }
         }

/*         // set pipe
         pipeout = checktopipe (tokens, curstart, nextstart);
         if (pipein) {
            fdin[0] = fdout[0];
            fdin[1] = fdout[1];
         }
         if (pipeout) {
            pipe (fdout);
         }
*/       
         // set redirection
         char *input_redirect = get_redirectarg (tokens, curstart, nextstart, '<');
         char *output_redirect = get_redirectarg (tokens, curstart, nextstart, '>');
         if (input_redirect != NULL) {
            // open file and set file descriptor
            fd[0] = open (input_redirect, O_RDONLY, 0755);
         }
         if (output_redirect != NULL) {
            // open file and set file descriptor
            fd[1] = open (output_redirect, O_CREAT | O_WRONLY | O_TRUNC, 0644);
         }


         // fork child process
         int status = 0;
         int pid = fork();
         if (pid != 0) {
            /* this is the PARENT PROCESS */
/*            // write to pipe from parent to child
            if (pipein) {
               close (fdin[0]);
               if (dup2 (fdin[1], STDOUT_FILENO) == -1)
                  eprintf ("%s: %s\n", "ERROR",
                           "could not open and write to pipe from parent to child");
               close (fdin[1]);
               pipein = FALSE;
               
            }
*/
            // wait for any child process to finish
            int waitstatus = waitpid (-1, &status, 0);

/*            // read pipe from child to parent
            if (pipeout) {
               close (fdout[1]);
               if (dup2 (fdout[0], STDIN_FILENO) == -1)
                  eprintf ("%s: %s\n", "ERROR",
                           "could not open and read pipe from child to parent");
               pipein = TRUE;
            }
*/          // close the file descriptors caused by redirection
            // close stdin
            if (input_redirect != NULL) close (fd[0]);
            // close stdout
            if (output_redirect != NULL) close (fd[1]);
            // determine errors
            if (waitstatus == 0) {
               eprintf ("%s: %s\n", "ERROR", "error waiting on child process");
               break;
            }else if (waitstatus == -1) {
               eprintf ("%s: %s\n", "ERROR", "error executing child process");
               break;
            }
            if (status != 0) {
               eprintf ("%s: %s: %s %d\n", "ERROR", command, "exit status of", status);
               break;
            }
         }else {
            /* this is the CHILD PROCESS */
            // set up pipe in from a previous command
/*            if (pipein) {
               close (fdin[1]);
               if (dup2 (fdin[0], STDIN_FILENO) == -1)
                  eprintf ("%s: %s\n", "ERROR",
                           "could not open and write to pipe from child to parent");
               close (fdin[0]);
            }
            // set up pipe out to the next command
            if (pipeout) {
               close (fdout[0]);
               if (dup2 (fdout[1], STDOUT_FILENO) == -1)
                  eprintf ("%s: %s\n", "ERROR",
                           "could not open and write to pipe from child to parent");
            }
*/            
            // set up redirection
            if (input_redirect != NULL) {
               // open file and set file descriptor
               // set file to stdin
               if (dup2 (fd[0], STDIN_FILENO) == -1)
                  eprintf ("%s: %s \"%s\" %s\n", "ERROR", "could not open",
                           input_redirect, "for input redirection");
            }
            if (output_redirect != NULL) {
               // open file and set file descriptor
               // set stdout to file
               if (dup2 (fd[1], STDOUT_FILENO) == -1)
                  eprintf ("%s: %s \"%s\" %s\n", "ERROR", "could not open",
                           output_redirect, "for output redirection");
            }

            // execute the command
            set_exitstatus (execvp (command, newargv));
            // if there was an error executing the command
            eprintf ("%s: %s: %s\n", "ERROR", command, "could not execute");
            return (get_exitstatus());
         }
         
      }

   }
   return get_exitstatus();
}
Example #17
0
File: reader.c Project: qyqx/wisp
/* Read a single sexp from the reader. */
object_t *read_sexp (reader_t * r)
{
  /* Check for a shebang line. */
  if (r->shebang == -1)
    {
      char str[2];
      str[0] = reader_getc (r);
      str[1] = reader_getc (r);
      if (str[0] == '#' && str[1] == '!')
	{
	  /* Looks like a she-bang line. */
	  r->shebang = 1;
	  consume_line (r);
	}
      else
	{
	  r->shebang = 0;
	  reader_putc (r, str[1]);
	  reader_putc (r, str[0]);
	}
    }

  r->done = 0;
  r->error = 0;
  push (r);
  print_prompt (r);
  while (!r->eof && !r->error && (list_empty (r) || stack_height (r) > 1))
    {
      int nc, c = reader_getc (r);
      switch (c)
	{
	case EOF:
	  r->eof = 1;
	  break;

	  /* Comments */
	case ';':
	  consume_line (r);
	  break;

	  /* Dotted pair */
	case '.':
	  nc = reader_getc (r);
	  if (strchr (" \t\r\n()", nc) != NULL)
	    {
	      if (r->state->dotpair_mode > 0)
		read_error (r, "invalid dotted pair syntax");
	      else if (r->state->vector_mode > 0)
		read_error (r, "dotted pair not allowed in vector");
	      else
		{
		  r->state->dotpair_mode = 1;
		  reader_putc (r, nc);
		}
	    }
	  else
	    {
	      /* Turn it into a decimal point. */
	      reader_putc (r, nc);
	      reader_putc (r, '.');
	      reader_putc (r, '0');
	    }
	  break;

	  /* Whitespace */
	case '\n':
	  r->linecnt++;
	  print_prompt (r);
	case ' ':
	case '\t':
	case '\r':
	  break;

	  /* Parenthesis */
	case '(':
	  push (r);
	  break;
	case ')':
	  if (r->state->quote_mode)
	    read_error (r, "unbalanced parenthesis");
	  else if (r->state->vector_mode)
	    read_error (r, "unbalanced brackets");
	  else
	    addpop (r);
	  break;

	  /* Vectors */
	case '[':
	  push (r);
	  r->state->vector_mode = 1;
	  break;
	case ']':
	  if (r->state->quote_mode)
	    read_error (r, "unbalanced parenthesis");
	  else if (!r->state->vector_mode)
	    read_error (r, "unbalanced brackets");
	  else
	    addpop (r);
	  break;

	  /* Quoting */
	case '\'':
	  push (r);
	  add (r, quote);
	  if (!r->error)
	    r->state->quote_mode = 1;
	  break;

	  /* strings */
	case '"':
	  buf_read (r, "\"");
	  add (r, parse_str (r));
	  reader_getc (r);	/* Throw away other quote. */
	  break;

	  /* numbers and symbols */
	default:
	  buf_append (r, c);
	  buf_read (r, " \t\r\n()[];");
	  object_t *o = parse_atom (r);
	  if (!r->error)
	    add (r, o);
	  break;
	}
    }
  if (!r->eof && !r->error)
    consume_whitespace (r);
  if (r->error)
    return err_symbol;

  /* Check state */
  r->done = 1;
  if (stack_height (r) > 1 || r->state->quote_mode
      || r->state->dotpair_mode == 1)
    {
      read_error (r, "premature end of file");
      return err_symbol;
    }
  if (list_empty (r))
    {
      obj_destroy (pop (r));
      return NIL;
    }

  object_t *wrap = pop (r);
  object_t *sexp = UPREF (CAR (wrap));
  obj_destroy (wrap);
  return sexp;
}
Example #18
0
int ss_listen (int sci_idx)
{
    char *cp;
    ss_data *info;
    sigret_t (*sig_int)(int), (*sig_cont)(int), (*old_sig_cont)(int);
    char input[BUFSIZ];
    char buffer[BUFSIZ];
    char *end = buffer;
#ifdef POSIX_SIGNALS
    sigset_t omask, igmask;
#else
    int mask;
#endif
    int code;
    jmp_buf old_jmpb;
    ss_data *old_info = current_info;
    
    current_info = info = ss_info(sci_idx);
    sig_cont = (sigret_t (*)(int)) 0;
    info->abort = 0;
#ifdef POSIX_SIGNALS
    sigemptyset(&igmask);
    sigaddset(&igmask, SIGINT);
    sigprocmask(SIG_BLOCK, &igmask, &omask);
#else
    mask = sigblock(sigmask(SIGINT));
#endif
    memcpy(old_jmpb, listen_jmpb, sizeof(jmp_buf));
    sig_int = signal(SIGINT, listen_int_handler);
    setjmp(listen_jmpb);
#ifdef POSIX_SIGNALS
    sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
#else
    (void) sigsetmask(mask);
#endif
    while(!info->abort) {
	print_prompt(0);
	*end = '\0';
	old_sig_cont = sig_cont;
	sig_cont = signal(SIGCONT, print_prompt);
	if (sig_cont == print_prompt)
	    sig_cont = old_sig_cont;
	if (fgets(input, BUFSIZ, stdin) != input) {
	    code = SS_ET_EOF;
	    goto egress;
	}
	cp = strchr(input, '\n');
	if (cp) {
	    *cp = '\0';
	    if (cp == input)
		continue;
	}
	(void) signal(SIGCONT, sig_cont);
	for (end = input; *end; end++)
	    ;

	code = ss_execute_line (sci_idx, input);
	if (code == SS_ET_COMMAND_NOT_FOUND) {
	    register char *c = input;
	    while (*c == ' ' || *c == '\t')
		c++;
	    cp = strchr (c, ' ');
	    if (cp)
		*cp = '\0';
	    cp = strchr (c, '\t');
	    if (cp)
		*cp = '\0';
	    ss_error (sci_idx, 0,
		    "Unknown request \"%s\".  Type \"?\" for a request list.",
		       c);
	}
    }
    code = 0;
egress:
    (void) signal(SIGINT, sig_int);
    memcpy(listen_jmpb, old_jmpb, sizeof(jmp_buf));
    current_info = old_info;
    return code;
}
Example #19
0
int main(int argc, char *argv[])
{
	int opt;
	bdaddr_t src_addr;
	int dev_id = -1;
	int fd;
	int sec = BT_SECURITY_LOW;
	uint8_t src_type = BDADDR_LE_PUBLIC;
	uint16_t mtu = 0;
	sigset_t mask;
	bool hr_visible = false;
	struct server *server;

	while ((opt = getopt_long(argc, argv, "+hvrs:t:m:i:",
						main_options, NULL)) != -1) {
		switch (opt) {
		case 'h':
			usage();
			return EXIT_SUCCESS;
		case 'v':
			verbose = true;
			break;
		case 'r':
			hr_visible = true;
			break;
		case 's':
			if (strcmp(optarg, "low") == 0)
				sec = BT_SECURITY_LOW;
			else if (strcmp(optarg, "medium") == 0)
				sec = BT_SECURITY_MEDIUM;
			else if (strcmp(optarg, "high") == 0)
				sec = BT_SECURITY_HIGH;
			else {
				fprintf(stderr, "Invalid security level\n");
				return EXIT_FAILURE;
			}
			break;
		case 't':
			if (strcmp(optarg, "random") == 0)
				src_type = BDADDR_LE_RANDOM;
			else if (strcmp(optarg, "public") == 0)
				src_type = BDADDR_LE_PUBLIC;
			else {
				fprintf(stderr,
					"Allowed types: random, public\n");
				return EXIT_FAILURE;
			}
			break;
		case 'm': {
			int arg;

			arg = atoi(optarg);
			if (arg <= 0) {
				fprintf(stderr, "Invalid MTU: %d\n", arg);
				return EXIT_FAILURE;
			}

			if (arg > UINT16_MAX) {
				fprintf(stderr, "MTU too large: %d\n", arg);
				return EXIT_FAILURE;
			}

			mtu = (uint16_t) arg;
			break;
		}
		case 'i':
			dev_id = hci_devid(optarg);
			if (dev_id < 0) {
				perror("Invalid adapter");
				return EXIT_FAILURE;
			}

			break;
		default:
			fprintf(stderr, "Invalid option: %c\n", opt);
			return EXIT_FAILURE;
		}
	}

	argc -= optind;
	argv -= optind;
	optind = 0;

	if (argc) {
		usage();
		return EXIT_SUCCESS;
	}

	if (dev_id == -1)
		bacpy(&src_addr, BDADDR_ANY);
	else if (hci_devba(dev_id, &src_addr) < 0) {
		perror("Adapter not available");
		return EXIT_FAILURE;
	}

	fd = l2cap_le_att_listen_and_accept(&src_addr, sec, src_type);
	if (fd < 0) {
		fprintf(stderr, "Failed to accept L2CAP ATT connection\n");
		return EXIT_FAILURE;
	}

	mainloop_init();

	server = server_create(fd, mtu, hr_visible);
	if (!server) {
		close(fd);
		return EXIT_FAILURE;
	}

	if (mainloop_add_fd(fileno(stdin),
				EPOLLIN | EPOLLRDHUP | EPOLLHUP | EPOLLERR,
				prompt_read_cb, server, NULL) < 0) {
		fprintf(stderr, "Failed to initialize console\n");
		server_destroy(server);

		return EXIT_FAILURE;
	}

	printf("Running GATT server\n");

	sigemptyset(&mask);
	sigaddset(&mask, SIGINT);
	sigaddset(&mask, SIGTERM);

	mainloop_set_signal(&mask, signal_cb, NULL, NULL);

	print_prompt();

	mainloop_run();

	printf("\n\nShutting down...\n");

	server_destroy(server);

	return EXIT_SUCCESS;
}
Example #20
0
int main(int argc, char *argv[])
{
	int opt;
	int sec = BT_SECURITY_LOW;
	uint16_t mtu = 0;
	uint8_t dst_type = BDADDR_LE_PUBLIC;
	bool dst_addr_given = false;
	bdaddr_t src_addr, dst_addr;
	int dev_id = -1;
	int fd;
	sigset_t mask;
	struct client *cli;

	while ((opt = getopt_long(argc, argv, "+hvs:m:t:d:i:",
						main_options, NULL)) != -1) {
		switch (opt) {
		case 'h':
			usage();
			return EXIT_SUCCESS;
		case 'v':
			verbose = true;
			break;
		case 's':
			if (strcmp(optarg, "low") == 0)
				sec = BT_SECURITY_LOW;
			else if (strcmp(optarg, "medium") == 0)
				sec = BT_SECURITY_MEDIUM;
			else if (strcmp(optarg, "high") == 0)
				sec = BT_SECURITY_HIGH;
			else {
				fprintf(stderr, "Invalid security level\n");
				return EXIT_FAILURE;
			}
			break;
		case 'm': {
			int arg;

			arg = atoi(optarg);
			if (arg <= 0) {
				fprintf(stderr, "Invalid MTU: %d\n", arg);
				return EXIT_FAILURE;
			}

			if (arg > UINT16_MAX) {
				fprintf(stderr, "MTU too large: %d\n", arg);
				return EXIT_FAILURE;
			}

			mtu = (uint16_t)arg;
			break;
		}
		case 't':
			if (strcmp(optarg, "random") == 0)
				dst_type = BDADDR_LE_RANDOM;
			else if (strcmp(optarg, "public") == 0)
				dst_type = BDADDR_LE_PUBLIC;
			else {
				fprintf(stderr,
					"Allowed types: random, public\n");
				return EXIT_FAILURE;
			}
			break;
		case 'd':
			if (str2ba(optarg, &dst_addr) < 0) {
				fprintf(stderr, "Invalid remote address: %s\n",
									optarg);
				return EXIT_FAILURE;
			}

			dst_addr_given = true;
			break;

		case 'i':
			dev_id = hci_devid(optarg);
			if (dev_id < 0) {
				perror("Invalid adapter");
				return EXIT_FAILURE;
			}

			break;
		default:
			fprintf(stderr, "Invalid option: %c\n", opt);
			return EXIT_FAILURE;
		}
	}

	if (!argc) {
		usage();
		return EXIT_SUCCESS;
	}

	argc -= optind;
	argv += optind;
	optind = 0;

	if (argc) {
		usage();
		return EXIT_SUCCESS;
	}

	if (dev_id == -1)
		bacpy(&src_addr, BDADDR_ANY);
	else if (hci_devba(dev_id, &src_addr) < 0) {
		perror("Adapter not available");
		return EXIT_FAILURE;
	}

	if (!dst_addr_given) {
		fprintf(stderr, "Destination address required!\n");
		return EXIT_FAILURE;
	}

	mainloop_init();

	fd = l2cap_le_att_connect(&src_addr, &dst_addr, dst_type, sec);
	if (fd < 0)
		return EXIT_FAILURE;

	cli = client_create(fd, mtu);
	if (!cli) {
		close(fd);
		return EXIT_FAILURE;
	}

	if (mainloop_add_fd(fileno(stdin),
				EPOLLIN | EPOLLRDHUP | EPOLLHUP | EPOLLERR,
				prompt_read_cb, cli, NULL) < 0) {
		fprintf(stderr, "Failed to initialize console\n");
		return EXIT_FAILURE;
	}

	sigemptyset(&mask);
	sigaddset(&mask, SIGINT);
	sigaddset(&mask, SIGTERM);

	mainloop_set_signal(&mask, signal_cb, NULL, NULL);

	print_prompt();

	mainloop_run();

	printf("\n\nShutting down...\n");

	client_destroy(cli);

	return EXIT_SUCCESS;
}
Example #21
0
int main(int argc, char **argv)
{
	int		i,j,len;
	int		argcount;
	char		arglist[100][256];
	char		**arg = NULL;
	char 		*buf;
	char 		*buffer;
	char		a[80];
	char		b[80];
	buf = (char *)malloc(256);					//分配空间
	buffer = (char *)malloc(80);
	if(buf == NULL) {
		printf("malloc failed\n");				//分配失败
		exit(-1);
	}

	while(1) {
		memset(buf, 0, 256);					//初始化数组
		print_prompt();						//输出提示符
		get_input(buf, &argcount, arglist);			//按空格分解命令
		if(strcmp(arglist[0], "cd") == 0) {
			if(argcount == 1) {
				chdir("/home/lxd");
			} else if(argcount == 2) {
				if(strcmp(arglist[1],"..") == 0) {
					 getcwd(buffer, 80);
					 len = strlen(buffer);
					 strcpy(a, buffer);
					 for(i=len; i>0; i--) {
						if(a[i] == '/'){
						a[i] = '\0';
						break;
						}
					}
					chdir(a);
				}

				else if(strcmp(arglist[1], ".") == 0){
					continue;
				} else if(strcmp(arglist[1],"~") == 0) {
					chdir("/home/lxd");
				} else {
					if(chdir(arglist[1]) == -1)
					printf("shu ru mulu bu zhengque\n");
 				}
			}
	}
		else if (do_cmd(&argcount, arglist) == 1){			//解析命令并执行
			wait(NULL);	getchar();			//等待子进程结束
			printf("已完成\n");
		}

	}

	if(buf != NULL) {
		free(buf);						//释放buf内存
		buf = NULL;
	}

	exit(0);
}
Example #22
0
File: input.c Project: dmt4/ne
static void input_autocomplete(void) {
	int dx = 0, prefix_pos = pos;
	char *p;

	/* find a usable prefix */
	if (prefix_pos && prefix_pos <= len) {
		prefix_pos = prev_pos(input_buffer, prefix_pos, encoding);
		dx--;
		while (prefix_pos && ne_isword(get_char(&input_buffer[prefix_pos], encoding), encoding)) {
			dx--;
			prefix_pos = prev_pos(input_buffer, prefix_pos, encoding);
		}
		if (! ne_isword(get_char(&input_buffer[prefix_pos], encoding), encoding)) {
			dx++;
			prefix_pos = next_pos(input_buffer, prefix_pos, encoding);
		}
		p = malloc(pos - prefix_pos + 1);
		if (!p) {
			alert(); /* OUT_OF_MEMORY */
			return;
		}
		strncpy(p, &input_buffer[prefix_pos], pos - prefix_pos);
	}
	else p = malloc(1); /* no prefix left of the cursor; we'll give an empty one. */
	p[pos - prefix_pos] = 0;

	int ac_err;
	if (p = autocomplete(p, NULL, true, &ac_err)) {
		encoding_type ac_encoding = detect_encoding(p, strlen(p));
		if (ac_encoding != ENC_ASCII && encoding != ENC_ASCII && ac_encoding != encoding) {
			free(p);
			alert();
		} else {
			encoding = ac_encoding;

			if (prefix_pos < pos) {
				memmove(&input_buffer[prefix_pos], &input_buffer[pos], len - pos + 1);
				len -= pos - prefix_pos;
				pos = prefix_pos;
			}
			int ac_len = strlen(p);
			if (ac_len + len >= MAX_INPUT_LINE_LEN) ac_len = MAX_INPUT_LINE_LEN - len;
			memmove(&input_buffer[pos + ac_len], &input_buffer[pos], len - pos + 1);
			memmove(&input_buffer[pos], p, ac_len);
			len += ac_len;
			while (ac_len > 0) {
				const int cw = get_char_width(&input_buffer[pos],encoding);
				pos = next_pos(input_buffer, pos, encoding);
				ac_len -= cw;
				dx++;
			}
			free(p); 
			x += dx;
			if (x >= ne_columns) {
				dx = x - ne_columns + 1;
				while (dx--) {
					offset = next_pos(input_buffer, offset, encoding);
				}
				x = ne_columns - 1;
			}
		}
	}
	if (ac_err == AUTOCOMPLETE_COMPLETED || ac_err == AUTOCOMPLETE_CANCELLED) {
		do_action(cur_buffer, REFRESH_A, 0, NULL);
		refresh_window(cur_buffer);
		set_attr(0);
		print_prompt(NULL);
	}
	input_refresh();
}
Example #23
0
/**
 * Process user input
 * This function only looks at a single character typed at a time.
 * Once it sees a newline character it will then call process_user
 * to process the user input
 */
int handle_user(){
	refresh();
	int c = getch();
	if(c == ERR){
		return 0;
	}
	switch(c){
		case '\n':
			if(process_user(buffer) != 0){
				return 1;
			}
			buffer_pos = 0;
			break;
		case KEY_F(4):
			close_interface();
			exit(0);
		case KEY_F(1):
		case KEY_F(2):
		case KEY_F(3):
		case KEY_F(5):
		case KEY_F(6):
		case KEY_F(7):
		case KEY_F(8):
		case KEY_F(9):
		case KEY_F(10):
		case KEY_F(11):
		case KEY_F(12):
			break;
		case KEY_UP:
		case KEY_DOWN:
			break;
		case KEY_LEFT:
			break;
		case KEY_RIGHT:
			break;
		case KEY_BACKSPACE:
		case KEY_DC:
			// delete the current character
			buffer[buffer_pos] = 0;
			buffer_pos --;
			// sanity check
			if(buffer_pos < 0){
				buffer_pos = 0;
			}
			buffer[buffer_pos] = 0;

			// ugly hack to clear the line, we rebuild the window >.<
			destroy_win(windows[INPUT_WIN]);
			windows[INPUT_WIN] = create_newwin(4, COLS, LINES-4, 0);
			print_prompt(windows[INPUT_WIN]);

			wprintw(windows[INPUT_WIN],"%s",buffer);
			wrefresh(windows[INPUT_WIN]);
			break;
		default:
			buffer[buffer_pos++] = (char)c;

			wprintw(windows[INPUT_WIN],"%c",c);
			wrefresh(windows[INPUT_WIN]);
	}
	return 0;

}
Example #24
0
File: input.c Project: dmt4/ne
char *request(const char *prompt, const char * const default_string, const bool alpha_allowed, const int completion_type, const bool prefer_utf8) {

	set_attr(0);

	input_buffer[pos = len = offset = 0] = 0;
	encoding = ENC_ASCII;
	x = start_x = print_prompt(prompt);

	init_history();

	if (default_string) {
		strncpy(input_buffer, default_string, MAX_INPUT_LINE_LEN);
		len = strlen(input_buffer);
		encoding = detect_encoding(input_buffer, len);
		input_refresh();
	}

	bool first_char_typed = true, last_char_completion = false, selection = false;

	while(true) {

		assert(input_buffer[len] == 0);

		move_cursor(ne_lines - 1, x);

		int c;
		input_class ic;
		do c = get_key_code(); while((ic = CHAR_CLASS(c)) == IGNORE);

		/* ISO 10646 characters *above 256* can be added only to UTF-8 lines, or ASCII lines (making them, of course, UTF-8). */
		if (ic == ALPHA && c > 0xFF && encoding != ENC_ASCII && encoding != ENC_UTF8) ic = INVALID;

		if (ic != TAB) last_char_completion = false;
		if (ic == TAB && !completion_type) ic = ALPHA;

		switch(ic) {

		case INVALID:
			alert();
			break;

		case ALPHA:

			if (first_char_typed) {
				input_buffer[len = 0] = 0;
				clear_to_eol();
			}

			if (encoding == ENC_ASCII && c > 0x7F) encoding = prefer_utf8 || c > 0xFF ? ENC_UTF8 : ENC_8_BIT;
			int c_len = encoding == ENC_UTF8 ? utf8seqlen(c) : 1;
			int c_width = output_width(c);
			assert(c_len > 0);

			if (len <= MAX_INPUT_LINE_LEN - c_len && (alpha_allowed || (c < 0x100 && isxdigit(c)) || c=='X' || c=='x')) {

				memmove(&input_buffer[pos + c_len], &input_buffer[pos], len - pos + 1);

				if (c_len == 1) input_buffer[pos] = c;
				else utf8str(c, &input_buffer[pos]);

				len += c_len;

				move_cursor(ne_lines - 1, x);

				if (x < ne_columns - c_width) {
					if (pos == len - c_len) output_char(c, 0, encoding);
					else if (char_ins_del_ok) insert_char(c, 0, encoding);
					else input_refresh();
				}

				input_move_right(true);
			}
			break;

		case RETURN:
			selection = true;
			break;

		case TAB:
			if (completion_type == COMPLETE_FILE || completion_type == COMPLETE_SYNTAX) {
				bool quoted = false;
				char *prefix, *completion, *p;
				if (len && input_buffer[len - 1] == '"') {
					input_buffer[len - 1] = 0;
					if (prefix = strrchr(input_buffer, '"')) {
						quoted = true;
						prefix++;
					}
					else input_buffer[len - 1] = '"';
				}

				if (!quoted) {
					prefix = strrchr(input_buffer, ' ');
					if (prefix) prefix++;
					else prefix = input_buffer;
				}

				if (last_char_completion || completion_type == COMPLETE_SYNTAX) {
					if (completion_type == COMPLETE_FILE )
						completion = p = request_files(prefix, true);
					else
						completion = p = request_syntax(prefix, true);
					reset_window();
					if (completion) {
						if (*completion) selection = true;
						else completion++;
					}
				}
				else {
					if (completion_type == COMPLETE_FILE )
						completion = p = complete_filename(prefix);
					else
						completion = p = request_syntax(prefix, true);
					last_char_completion = true;
					if (!completion) alert();
				}

				if (completion && (prefix - input_buffer) + strlen(completion) + 1 < MAX_INPUT_LINE_LEN) {
					const encoding_type completion_encoding = detect_encoding(completion, strlen(completion));
					if (encoding == ENC_ASCII || completion_encoding == ENC_ASCII || encoding == completion_encoding) {
						strcpy(prefix, completion);
						if (quoted) strcat(prefix, "\"");
						len = strlen(input_buffer);
						pos = offset = 0;
						x = start_x;
						if (encoding == ENC_ASCII) encoding = completion_encoding;
						input_move_to_eol();
						if (quoted) input_move_left(false);
						input_refresh();
					}
					else alert();
				}
				else if (quoted) strcat(prefix, "\"");

				free(p);
			}
			break;

		case COMMAND:
			if (c < 0) c = -c - 1;
			const int a = parse_command_line(key_binding[c], NULL, NULL, false);
			if (a >= 0) {
				switch(a) {

				case LINEUP_A:
				case LINEDOWN_A:
				case MOVESOF_A:
				case MOVEEOF_A:
				case PAGEUP_A:
				case PAGEDOWN_A:
				case NEXTPAGE_A:
				case PREVPAGE_A:
					if (history_buff) {
						switch(a) {
						case LINEUP_A: line_up(history_buff); break;
						case LINEDOWN_A: line_down(history_buff); break;
						case MOVESOF_A: move_to_sof(history_buff); break;
						case MOVEEOF_A: move_to_bof(history_buff); break;
						case PAGEUP_A:
						case PREVPAGE_A: prev_page(history_buff); break;
						case PAGEDOWN_A:
						case NEXTPAGE_A: next_page(history_buff); break;
						}

						/* In some cases, the default displayed on the command line will be the same as the 
							first history item. In that case we skip it. */

						if (first_char_typed == true 
							 && a == LINEUP_A 
							 && history_buff->cur_line_desc->line 
							 && !strncmp(history_buff->cur_line_desc->line, input_buffer, history_buff->cur_line_desc->line_len))
							line_up(history_buff);

						if (history_buff->cur_line_desc->line) {
							strncpy(input_buffer,
									  history_buff->cur_line_desc->line,
									  min(history_buff->cur_line_desc->line_len,MAX_INPUT_LINE_LEN));
							input_buffer[min(history_buff->cur_line_desc->line_len,MAX_INPUT_LINE_LEN)] = 0;
							len	 = strlen(input_buffer);
							encoding = detect_encoding(input_buffer, len);
						}
						else {
							input_buffer[len = 0] = 0;
							encoding = ENC_ASCII;
						}

						x		= start_x;
						pos	= 0;
						offset = 0;
						input_refresh();
					}
					break;

				case MOVELEFT_A:
					input_move_left(true);
					break;

				case MOVERIGHT_A:
					input_move_right(true);
					break;

				case BACKSPACE_A:
					if (pos == 0) break;
					input_move_left(true);

				case DELETECHAR_A:
					if (len > 0 && pos < len) {
						int c_len = encoding == ENC_UTF8 ? utf8len(input_buffer[pos]) : 1;
						int c_width = get_char_width(&input_buffer[pos], encoding);
						memmove(&input_buffer[pos], &input_buffer[pos + c_len], len - pos - c_len + 1);
						len -= c_len;
						if (input_buffer_is_ascii()) encoding = ENC_ASCII;

						if (char_ins_del_ok) {
							int i, j;

							move_cursor(ne_lines - 1, x);
							delete_chars(c_width);

							for(i = x, j = pos; j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns - c_width; i += get_char_width(&input_buffer[j], encoding), j = next_pos(input_buffer, j, encoding));

							if (j < len) {
								move_cursor(ne_lines - 1, i);
								while(j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns) {
									output_char(get_char(&input_buffer[j], encoding), 0, encoding);
									i += get_char_width(&input_buffer[j], encoding);
									j = next_pos(input_buffer, j, encoding);
								}
							}
						}
						else input_refresh();
					}
					break;

				case DELETELINE_A:
					move_cursor(ne_lines - 1, start_x);
					clear_to_eol();
					input_buffer[len = pos = offset = 0] = 0;
					encoding = ENC_ASCII;
					x = start_x;
					break;

				case DELETEEOL_A:
					input_buffer[len = pos] = 0;
					clear_to_eol();
					if (input_buffer_is_ascii()) encoding = ENC_ASCII;
					break;

				case MOVEINCUP_A:
					if (x != start_x) {
						pos = offset;
						x = start_x;
						break;
					}

				case MOVESOL_A:
					input_move_to_sol();
					break;

				case MOVEINCDOWN_A: {
					int i, j;
					for(i = x, j = pos; j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns; i += get_char_width(&input_buffer[j], encoding), j = next_pos(input_buffer, j, encoding));
					if (j != pos && j < len) {
						pos = j;
						x = i;
						break;
					}
				}

				case MOVEEOL_A:
					input_move_to_eol();
					break;

				case TOGGLESEOL_A:
				case TOGGLESEOF_A:
					if (pos != 0) input_move_to_sol();
					else input_move_to_eol();
					break;

				case PREVWORD_A:
					input_prev_word();
					break;

				case NEXTWORD_A:
					input_next_word();
					break;

				case REFRESH_A:
					input_refresh();
					break;

				case PASTE_A:
					input_paste();
					break;

				case AUTOCOMPLETE_A:
					input_autocomplete();
					break;

				case ESCAPE_A:
					return NULL;

				default:
					break;
				}
			}
			break;

		default:
			break;
		}

		if (selection) {
			const line_desc * const last = (line_desc *)history_buff->line_desc_list.tail_pred->prev;
			assert(input_buffer[len] == 0);
			if (history_buff->num_lines == 0 || len != last->line_len || strncmp(input_buffer, last->line, last->line_len)) add_to_history(input_buffer);
			return input_buffer;
		}

		first_char_typed = false;
	}
}
Example #25
0
// main function
int 
main (int argc, char *argv[]){
    print_prompt();  
    FILE *stream = NULL;
    //char void_input[512];
    char *tmp_input = NULL;
    char *history[History_Max]; 
    int is_internal = 0;
    int is_redir = 0;
    int i;
    int current = 0;
    for(i = 0; i < History_Max; i++){
        history[i] = NULL;    
    }   
    // Judge a file is a batch or not
    if (argc == 1){
        stream = stdin;  
    }
    else if (argc == 2){
        is_batch = 1;
        stream = fopen(argv[1], "r");
        if (stream == NULL){
            print_error();
            exit(1);
        }  
    }
    else{
         print_error();
         exit(1);
    }

   // Tell whether it is a valid input command
    while (fgets(input, in_size, stream)){
        // if the input is too large
        if (strlen(input) > 513){ // 513 includes the EOF
            if (is_batch){ 
	        write(STDOUT_FILENO, input, strlen(input));
                print_prompt();
                continue;
            }
            print_error();
            print_prompt();
            continue;    
	}
	is_internal = 0;
	is_redir = 0;			

        // if the input is empty, output the shell command
     //   if (compare(input, void_input) == 1){ //strcmp cannot compare a null string with another null string   /// still have confusion
       //     print_prompt();
         //   continue;   
      //  }

        // redirection
        char *pre_redir = NULL;
        char *post_redir = NULL;
        tmp_input = strdup(input);
        pre_redir = strtok(tmp_input, ">");
        if (strlen(pre_redir) != strlen(input)){
            is_redir =1; 
            post_redir = strtok(NULL, " "); // why use NULL?
            if (strtok(NULL, ">")){ // too many input
	        is_redir = 0;
                print_error();
                print_prompt();
                continue;
            }
        }
 
        // get word count 
         word_cnt = sep_line(input, words);
        
        //create history
	if(input[strlen(input) - 1] == '\n'){ 
	    input[strlen(input) - 1] = '\0';
	}
	free(history[current]);
        history[current] = strdup(input);
        his_num++; 
        current  = (current + 1) % History_Max;
        
        // check for redirection output file is valid or not
        int fd_out = 0;
        if (is_redir){

	    int dump = dup(STDOUT_FILENO);
	    close(STDOUT_FILENO);

            fd_out = open(words[word_cnt-1], O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU); 
            if (fd_out < 0){
                print_error();
                print_prompt();
                continue; 
            }

	    close(fd_out);
	    dup2(dump,STDOUT_FILENO);
	    close(dump);
	}

        // Internal command
        // exit
        char *str_exit = "exit";
        if (!strcmp(str_exit, input)){
            if (word_cnt != 1){
                print_error();
                print_prompt();
            }
            else {
		is_internal = 1;
		exit(0);
            }        
        }
       
	//print history
        char *str_history = "history";
	if (!strcmp(str_history, input)){
	    if (word_cnt != 1){
		print_error();
		print_prompt();
	    }
	    else {
	        is_internal = 1;
		print_history(history, current);
	    }
        }

        // fork and execvp, how to deal with fork and child is still undefined
        int child; 
        if (!is_internal){
            child = fork();
            if (child == 0){
                execvp(words[0], words); 
                print_error();
                exit(1); 
	    }
	    else if(child > 0) {
		   (void)wait(NULL);
	    }
	    else {
                print_error();
            }
        }
    print_prompt();
    }//end while loop
    clear_history(history);
    return 0;        
}
Example #26
0
void main_loop() {
    char *cs;
    int index;
    int n_match;
    int scroll = 0;

#ifdef USE_XSELECTION
    cs = check_sel();
#endif
    if(cs)
        edit_set_text(cs);

    n_match = myd_bsearch(myd, edit.text, &index);
    display(myd, index, n_match, scroll);
    print_prompt(edit.text, edit.cursor);

    while(1) {
        int c;

        c = term_getch();

        if(isprint(c)) {
            edit_ins_char(c);
            n_match = myd_bsearch(myd, edit.text, &index);
            scroll = 0;
        } else {
            switch(c) {
            /*
             *    move cursor
             */
            case 1:  /* ^A */
                edit_cur_head();
                move_cursor(edit.cursor);
                continue;
            case 2:  /* ^B */
            case KEY_LEFT:
                edit_cur_back();
                move_cursor(edit.cursor);
                continue;
            case 5:  /* ^E */
                edit_cur_tail();
                move_cursor(edit.cursor);
                continue;
            case 6:  /* ^F */
            case KEY_RIGHT:
                edit_cur_forward();
                move_cursor(edit.cursor);
                continue;


            /*
             *    scroll
             */
            case 16: /* ^P */
            case KEY_PPAGE:
            case KEY_UP:
                if(scroll == 0)
                    continue;
                scroll -= SCROLL_STEP;
                if(scroll < 0)
                    scroll = 0;
                break;
            case 14: /* ^N */
            case KEY_NPAGE:
            case KEY_DOWN:
                if(scroll == n_match - 1)
                    continue;
                scroll += SCROLL_STEP;
                if(scroll >= n_match)
                    scroll = n_match - 1;
                break;


            /*
             *   delete text
             */
            case 8:  /* ^H */
                edit_back_space();
                n_match = myd_bsearch(myd, edit.text, &index);
                scroll = 0;
                break;
            case 4:  /* ^D */
            case 0x7f:
                edit_del_char();
                n_match = myd_bsearch(myd, edit.text, &index);
                scroll = 0;
                break;
            case 21: /* ^U */
            case 10: /* ^J */
            case 13: /* ^M */
                edit_clear();
                n_match = myd_bsearch(myd, edit.text, &index);
                scroll = 0;
                break;
            case 11: /* ^K */
                edit_kill();
                n_match = myd_bsearch(myd, edit.text, &index);
                scroll = 0;
                break;

            case 20: /* ^T */
                edit_transpose();
                n_match = myd_bsearch(myd, edit.text, &index);
                scroll = 0;
                break;

            case 12: /* ^L */
                break;

            /*  Exit */
            case 24: /* ^X */
                return;

            case ERR: /* timeout */
#ifdef USE_XSELECTION
                cs = check_sel();
#endif
                if(cs) {
                    edit_set_text(cs);
                    n_match = myd_bsearch(myd, edit.text, &index);
                    scroll = 0;
                    break;
                } else
                    continue;

            default:
                break;
            }
        }
        display(myd, index, n_match, scroll);
        print_prompt(edit.text, edit.cursor);
    }
}
Example #27
0
void terminal_init(void)
{
	ptr = command_buffer;
	serio_write_str("\r\nUnicon Terminal, by Nathaniel Abalos\r\n");
	print_prompt();
}
Example #28
0
/*
 * Play one game of Hangperson.  The secret word is passed as a
 * parameter.  The function should return true if the player won,
 * and false otherwise.
 */
bool one_game(const char *word) {
    char wordLength = get_length(word);
    char num_missed = 0;
    bool game_over = false;
    char input[1024];


    // Create a string containing the secret word
    char secretWord[wordLength+1];
    strcpy(&secretWord, word);
    printf("The secret word is: %s\n",secretWord);
    printf("Length of word is: %d\n", wordLength);

    // Create a string representing the guessing state
    char currWord[wordLength+1];
    for (char i = 0; i < wordLength; i++) {
        currWord[i] = '_';
    }
    currWord[wordLength] = '\0';  
    
    // Create an array to track guessed character
    char guessedChar[27];
    guessedChar[0] = '\0';

    while (!game_over) {
        bool good_input = false;
        print_gallows(num_missed);
        printf("%s\n", currWord);
        char guess = 'a';
        while (!good_input) { // Loop until a single alphabet char is typed in
            print_prompt(guessedChar);
            fgets(input, 1024, stdin);
            if (feof(stdin)) {
                clearerr(stdin);
                print_tryagain();
                continue;
            } else if (input[0] == '\0' || input[1] != '\n') {
                print_tryagain();
                continue;
            } else if (!isalpha(input[0])) {
                print_tryagain();
                continue;
            } else {
                guess = toupper(input[0]);
                if (in_str(guess, &guessedChar)) {
                    printf("You already guessed %c\n", guess);
                    continue;
                }
                good_input = true;
            }  
        } 

       
        append(guess, &guessedChar);
        if (in_str(guess, &secretWord)) {
            printf("Good guess.\n");
            update_curr(guess, &secretWord, &currWord);
            if (is_guessed(&currWord)){
                game_over = true;
                break;
            }
        } else {
            printf("Bad guess.\n");
            num_missed += 1;
            if (num_missed >= 7) {
                game_over = true;
                print_gallows(num_missed);
                break;                        
            }
        }
        
        printf("Missed: %d\n",num_missed);              
        good_input = true; 


    }
    
    if (num_missed >= 7) {
        printf("You lost.\n");
    } else {
        printf("You won.\n");
    }
    
    printf("The word is: %s\n", secretWord);
}
Example #29
0
/**
 * @brief  启动work进程
 * @param
 * @return
 */
int run_work_proc(int argc, char *argv[], bool /* use_barrier */)
{
    setproctitle("%s:[WORK]", g_bench_conf.prog_name);
    
    if (dll.handle_init != NULL && dll.handle_init(argc, argv, PROC_WORK) != 0) {
        print_prompt(false, "Worker process handle_init failed.");
        return -1;
    }

    /// 由于环形队列中有头 shm_block_t,所以需要给头预留空间
    int prcv_data_len = g_bench_conf.max_pkg_len + sizeof(shm_block_t);
    char *prcv_data = (char *)malloc(prcv_data_len);

    if (prcv_data == NULL) {
        print_prompt(false, "Malloc work proc pop buffer fail, size: %d B", prcv_data_len);
        return -1;
    }

    shm_block_t *mb = (shm_block_t *)prcv_data;
    int sndlen = 0;
    int ret = 0;
    char *puser_data = NULL;

    if (g_bench_conf.use_barrier == true) {
        if (g_prcv_brq == NULL) {
            print_prompt(false, "Use barrier mode, but i_barrier_ring_queue is null.");
            goto work_proc_end;
        }

        while (! g_stop) {
            if (dll.handle_schedule) {
                dll.handle_schedule();
            }

            if (!g_prcv_brq->is_able_pop()) {
                /// 等待数据
                struct timespec tv = {0, 200000};
                nanosleep(&tv, NULL);
                continue;
            }

            AFUTEX_LOCK_ERR_CHK(g_rcv_rq_lock);
            ret = g_prcv_brq->pop(prcv_data, prcv_data_len);
            AFUTEX_UNLOCK_ERR_CHK(g_rcv_rq_lock);
            if (ret < 0) {
                ERROR_LOG("Barrier pop error: %d", g_prcv_brq->get_last_errno());
                sleep(1);  /// 防止出错以后打印日志速度太快
                continue;
            } else if (ret == 0) {
                /// 没有取出任何数据
                continue;
            } else {
                if(ret != mb->length || (u_int)mb->length <= sizeof(shm_block_t) || 
                   mb->length > prcv_data_len) {
                    /// 数据包包长有误,关闭这个连接
                    ERROR_LOG("Pop data len(%d) err, pkg len(%d), prcv_data_len(%d), shm_block_t(%zd), close conn: %d.",
                            ret, mb->length, prcv_data_len, sizeof(shm_block_t), mb->blk_id);
                    work_proc_close_conn(mb);
                    continue;
                }
            }

            TRACE_LOG("Pop barrier ring queue len: %d", mb->length);

            sndlen = 0;
            ret = dll.handle_process(mb->data, mb->length - sizeof(shm_block_t), &puser_data, &sndlen, &mb->skinfo);

            if (ret != 0) {
                work_proc_close_conn(mb);
                TRACE_LOG("Handle_process fail, close conn: %d", mb->blk_id);
            } else if(sndlen + sizeof(shm_block_t) > (u_int)prcv_data_len) {
                work_proc_close_conn(mb);
                ERROR_LOG("Handle_process sndlen(%d) > buf len, close conn: %d", sndlen, mb->blk_id);
            } else {
                if (sndlen > 0) {
                    mb->length = sndlen + sizeof(shm_block_t);
                    mb->type = DAT_BLOCK;
                    memcpy(mb->data, puser_data, sndlen);

                    AFUTEX_LOCK_ERR_CHK(g_snd_rq_lock);
                    ret = g_psnd_rq->push_data(prcv_data, mb->length, true);
                    AFUTEX_UNLOCK_ERR_CHK(g_snd_rq_lock);

                    if (ret != mb->length) {
                        ERROR_LOG("Push data(len: %d) error (ret: %d, data: %d, empty: %d)", mb->length,
                                  g_psnd_rq->get_last_errno(), g_psnd_rq->get_data_len(), g_psnd_rq->get_empty_buffer_len());
                    } else {
                        TRACE_LOG("ring queue push data len: %d", mb->length);
                        g_p_net_io_notifier->popup();
                    }
                }
            }
        }
    } else {
        if (g_prcv_rq == NULL) {
            print_prompt(false, "Use nonbarrier mode, but i_ring_queue object is null.");
            goto work_proc_end;
        }

        while (!g_stop) {
            if (dll.handle_schedule != NULL) {
                dll.handle_schedule();
            }

            if (g_prcv_rq->get_data_len() <= 0) {
                struct timespec tv = {0, 200000};
                nanosleep (&tv, NULL);
                continue;
            }

            AFUTEX_LOCK_ERR_CHK(g_rcv_rq_lock);
            ret = g_prcv_rq->pop_data(prcv_data, prcv_data_len, 0);
            AFUTEX_UNLOCK_ERR_CHK(g_rcv_rq_lock);
            if (ret < 0) {
                ERROR_LOG("Common ring queue pop fail(ret: %d): %s", ret, g_prcv_rq->get_last_errstr());
                sleep(1); /// 防止日志打印过快
                continue;
            } else if (ret == 0) {
                /// 数据还没准备好
                continue;
            } else {
                if(ret != mb->length || (u_int)mb->length <= sizeof(shm_block_t) || mb->length > prcv_data_len) {
                    /// 数据包包长有误,关闭这个连接
                    ERROR_LOG("Pop data len(%d) err, pkg len(%d), prcv_data_len(%d), shm_block_t(%zd), close conn: %d.",
                            ret, mb->length, prcv_data_len, sizeof(shm_block_t), mb->blk_id);
                    work_proc_close_conn(mb);
                    continue;
                }
            }
            TRACE_LOG("Common ring queue pop len: %d", mb->length);

            sndlen = 0;
            ret = dll.handle_process(mb->data, mb->length - sizeof(shm_block_t), &puser_data, &sndlen, &mb->skinfo);
            if (ret != 0) {
                work_proc_close_conn(mb);
                TRACE_LOG("Handle process fail, close conn: %d", mb->blk_id);
            } else if(sndlen + sizeof(shm_block_t) > (u_int)prcv_data_len) {
                work_proc_close_conn(mb);
                ERROR_LOG("Handle_process sndlen(%zd) > buf len %d, close conn: %d",
                        sndlen + sizeof(shm_block_t), prcv_data_len, mb->blk_id);
            } else {
                if (sndlen > 0) {
                    mb->length = sndlen + sizeof(shm_block_t);
                    mb->type = DAT_BLOCK;
                    memcpy(mb->data, puser_data, sndlen);

                    AFUTEX_LOCK_ERR_CHK(g_snd_rq_lock);
                    ret = g_psnd_rq->push_data(prcv_data, mb->length, true);
                    AFUTEX_UNLOCK_ERR_CHK(g_snd_rq_lock);

                    if (ret != mb->length) {
                        ERROR_LOG("Push data(len: %d) error (ret: %d, data: %d, empty: %d)", mb->length,
                                g_psnd_rq->get_last_errno(), g_psnd_rq->get_data_len(), g_psnd_rq->get_empty_buffer_len());
                    } else {
                        TRACE_LOG("Common ring queue push len: %d", mb->length);
                        g_p_net_io_notifier->popup();
                    }
                }
            }
        }
    }

work_proc_end:
    free(prcv_data);
    if (g_p_send_buff != NULL) {
        free(g_p_send_buff);
        g_p_send_buff = NULL;
        g_send_buff_len = 0;
    }
    if (dll.handle_fini != NULL) {
        dll.handle_fini(PROC_WORK);
    }
    return 0;
}
Example #30
0
int main(int argc, char ** argv)
{
	//get command line arguments
	int c;
    char * pvalue = NULL;
	while ((c = getopt (argc, argv, "p:")) != -1)
	{
		switch (c)
		{
			case 'p':
                pvalue = optarg;
				break;
			default:
				break;
		}
	}

	int cmd_type; //enumerated value to determine how command is executed
	int cmd_block; //whether to wait for child to exit or not
    int cmd_argc; //number of args counted while parsing
	char cmd_args[MAX_ARG_COUNT][MAX_INPUT_LENGTH]; //store command line args
    char * exec_args[MAX_ARG_COUNT]; //cmd_args incompatible type with execvp

	//ready prompt
	char prompt[MAX_INPUT_LENGTH];
	init_prompt(prompt);
	if(pvalue != NULL)
	{   
		change_prompt(prompt,pvalue);
	}

	char buffer[MAX_INPUT_LENGTH]; //general purpose string buffer
	
	int done = 0;
	do
	{
		//clear command buffer
		int i;
		for(i = 0; i < MAX_ARG_COUNT; i++)
		{
			cmd_args[i][0] = '\0';
		}
		//get input
		print_prompt(prompt);
		scanf("\n");
		scanf("%[^\n]",buffer);

		//store history
        strcpy(history[history_count],buffer);
        history_count++;

		//tokenize
		char * ptr = strtok(buffer," ");
		i = 0;
		while(ptr != NULL)
		{
			strcpy(cmd_args[i],ptr);
			ptr = strtok(NULL," ");
			i++;
		}
        argc = i;

		//set state based on input
		cmd_type = get_type(cmd_args[0]);
		cmd_block = get_block(cmd_args[argc-1]);
        int j;
        for(j = 0; j < argc; j++)
        {
            exec_args[j] = cmd_args[j];
        }
        if(!cmd_block) //want to eliminate &
        {
            exec_args[argc-1] = NULL;
        }
        else //keep all args parsed
        {
            exec_args[argc] = NULL;
        }
        
		//check if any children exited
		int status, child_pid;
		child_pid = waitpid(-1,&status,WNOHANG);
		if(child_pid > 0)
		{
			get_status_str(status,child_pid,buffer);
			print_out(buffer);
		}
        
        //execute
        done = execute(cmd_type,cmd_block,cmd_args[0],exec_args);

	}while(!done);
	return 0;
}