コード例 #1
0
ファイル: history.cpp プロジェクト: Maximus5/clink
//------------------------------------------------------------------------------
static bool print_history(const char* arg)
{
    if (arg == nullptr)
    {
        print_history(INT_MIN);
        return true;
    }

    // Check the argument is just digits.
    for (const char* c = arg; *c; ++c)
        if (unsigned(*c - '0') > 10)
            return false;

    print_history(atoi(arg));
    return true;
}
コード例 #2
0
ファイル: fash.c プロジェクト: dfritter4/Fash-Shell
int check_builtin(char *cmd)
{
	/* Arguments:
			cmd = program to run
			
		Purpose:
			this function checks to see if the 
			cmd specified is a built in command
			(in this case only "cd" is built-in)
		
		Returns:
			0  -- if the cmd is built in
			-1 -- if the cmd is NOT built in
	*/

	if(!strcmp(cmd,"cd")) {
		//command was "cd" which is a builtin, so
		//lets handle it
		add_nav_history(fullPath);
		chdir(args[1]); //change directory to first argument
		get_path();
	}
	else if(cmd[0] == '!') {
		//theyre requesting some sort of history
		exec_history(cmd); //execute the argument number 
	}
	else if(cmd[0] == '@') {
		//requesting nav history
		exec_nav_history(cmd);
		get_path();
	}
	else if(!strcmp(cmd,"history")) {
		print_history();
	}
	else if(!strcmp(cmd, "navhist")) {
		print_nav_history();
	}
	else if(!strcmp(cmd,"alias")) {
		//trying to set an alias
		if(args[1] == NULL) {
			//no argument, so just print all
			print_aliases();
		} else {
			add_alias(args[1]);
		}
	}
	else if(!strcmp(cmd,"unalias")) {
		//trying to remove an alias (args[1] is what is being removed)
		remove_alias(args[1]);
	}
	else if(!strcmp(cmd,"cinterp")) {
		//want to use the C interpreter
		//quit raw mode first (will make the cinterp easier)
		quit_raw_mode();
		cinterp();
		tty_raw_mode(); //reenter raw mode
	}
	else { return -1; }
	return 0;
}
コード例 #3
0
ファイル: events.c プロジェクト: taysom/tau
int main (int argc, char *argv[])
{
	punyopt(argc, argv, NULL, NULL);
	start_threads(Option.numthreads);
	print_history(&History, ARRAY_SIZE(Event_name), Event_name);
	return 0;
}
コード例 #4
0
ファイル: history.cpp プロジェクト: Maximus5/clink
//------------------------------------------------------------------------------
int history(int argc, char** argv)
{
    // Check to see if the user asked from some help!
    for (int i = 1; i < argc; ++i)
        if (_stricmp(argv[1], "--help") == 0 || _stricmp(argv[1], "-h") == 0)
            return print_help();

    // Try Bash-style arguments first...
    int bash_ret = history_bash(argc, argv);
    if (optind != 1)
        return bash_ret;

    // ...and the try Clink style arguments.
    if (argc > 1)
    {
        const char* verb = argv[1];

        // 'clear' command
        if (_stricmp(verb, "clear") == 0)
            return clear();

        // 'delete' command
        if (_stricmp(verb, "delete") == 0)
        {
            if (argc < 3)
            {
                puts("history: argument required for verb 'delete'");
                return print_help();
            }
            else
                return remove(atoi(argv[2]));
        }

        str<> line;

        // 'add' command
        if (_stricmp(verb, "add") == 0)
        {
            get_line(2, argc, argv, line);
            return line.empty() ? print_help() : add(line.c_str());
        }

        // 'expand' command
        if (_stricmp(verb, "expand") == 0)
        {
            get_line(2, argc, argv, line);
            return line.empty() ? print_help() : print_expansion(line.c_str());
        }
    }

    // Failing all else try to display the history.
    if (argc > 2)
        return print_help();

    const char* arg = (argc > 1) ? argv[1] : nullptr;
    if (!print_history(arg))
        return print_help();

    return 0;
}
コード例 #5
0
ファイル: test.c プロジェクト: garodimb/rtos
int test_realloc(){
	int index=0;
	size_t new_size,old_free_space,new_free_space;
	uint8_t *add;
	print_history();
	printf("Enter index to choose address: ");
	scanf("%d",&index);
	if(index>=ALLOC_HISTORY){
		printf("Invalid Selection\nTEST FAILED\n");
		return 1;
		}
	printf("Enter new size: ");
	scanf("%lu",&new_size);
	old_free_space = free_space_in_my_heap();
	
	/* Reallocate memory */
	add = (uint8_t *)my_realloc((void *)address[index],new_size);
	new_free_space = free_space_in_my_heap();
	
	/* Add to history for tracking */
	if(add!=NULL && add!=address[index]){
		address[pos]=add;
		pos = (pos+1)%ALLOC_HISTORY;
		}
		
	/* NULL address with size greater than 0 should work like malloc */
	if(address[index]==NULL && new_size > 0){
		if(add!=NULL && (new_free_space < old_free_space)){
			printf("TEST PASEED\n");
			return 0;
			}
		printf("TEST FAILED\n");
		return 1;
		}
	
	/* Not NULL address and size greater than 0, may shrink or expand memory */
	if(address[index]!=NULL && new_size > 0){
		if(add!=NULL){
			printf("TEST PASSED\n");
			return 0;
			}
		printf("TEST FAILED\n");
		return 1;
		}
	
	/* Not NULL address and size equal to zero should work like free */
	if(address[index]!=NULL && new_size==0){
		if(add==NULL && (new_free_space > old_free_space)){
			printf("TEST PASSED\n");
			return 0;
			}
		printf("TEST FAILED\n");
		return 1;
		}
	printf("TEST FAILED\n");	
	return 0;
	}
コード例 #6
0
ファイル: assignment01.c プロジェクト: djiglesias/COMPSCI
void shell_loop(char *prompt) {
	// Initiate parameters
	pid_t pid;
	char *p = strcat(prompt, "> ");
	int state = 1;
	int status = 0;
	char cmd[40];
	char input_line[MAX], *tokens[CMD_MAX];
	int i, n;

	// Initiate command history
	Hist hist[10];
	int length = 10;
	int index = 0;

	// Initiate shell environment
	while (state) {

		// Print line prompt
		printf("%s", p);

		// Extract tokens from user input
		if (fgets(input_line, MAX, stdin) != NULL)
			n = make_tokenlist(input_line, tokens, cmd);

		// Run specified command
		if (strcmp(tokens[0], "exit") == 0) {
			// Exit to main()
			return;

		}
		else if (strcmp(tokens[0], "history") == 0) {
			// Print command history
			print_history(hist, &index);

		}
		else {
			// Execute command from tokens
			strcpy(hist[index % 10].cmd, cmd);
			index++;
			run_command(tokens, n);

		} // end of if

		strcpy(cmd, "");

	} // end of while
}
コード例 #7
0
ファイル: test.c プロジェクト: garodimb/rtos
/* Test free function */	
int test_free(){
	int index=0;
	print_history();
	printf("Enter index to choose address: ");
	scanf("%d",&index);
	
	/* Check for invalid selection */
	if(index>=ALLOC_HISTORY){
		printf("Invalid Selection\nTEST FAILED\n");
		return 1;
		}
		
	/* Free memory block pointed by address(Data address) */
	my_free((void *)address[index]);
	printf("TEST PASSED\n");
	return 0;
	}
コード例 #8
0
ファイル: bt_history.c プロジェクト: IohannRabeson/42sh
void		bt_history(t_cmd *cmd, struct s_env *env)
{
	t_app *const	app = app_instance();
	t_getopt		go;

	if (cmd->argc == 1)
	{
		print_history();
		return ;
	}
	getopt_init_args(&go, cmd->argc, cmd->args);
	if (getopt_contains(&go, "-c"))
		histo_clear(&app->histo);
	else if (getopt_contains(&go, "-d"))
		remove_item_history(cmd);
	else if (getopt_contains(&go, "-r"))
		reload_history();
	getopt_destroy(&go);
	(void)env;
}
コード例 #9
0
ファイル: debug.cpp プロジェクト: dontpanic42/KarouGB
 bool Debugger::run_repl()
 {
     fmt::print_prompt(c, *mmu);
     
     
     switch(inp::get<char>("%c"))
     {
         case 'r': mode = RUN; return true;
         case 'x': print_cpu_status(std::cout); return run_repl();
         case 'g': print_gpu_status(std::cout); return run_repl();
         case 'h': print_ghw_status(std::cout); return run_repl();
         case '+': set_breakpoint(); return run_repl();
         case '-': rem_breakpoint(); return run_repl();
         case 'i': inspect(std::cout); return run_repl();
         case 'l': print_history(std::cout); return run_repl();
         case 'q': return false;
         case '?': {
             std::cout << "Interactive debugger:" << std::endl << std::endl;;
             std::cout << "(Press ESC while running to enter STEP-Mode)" << std::endl << std::endl;
             std::cout << "   'r': Run programm" << std::endl;
             std::cout << "   'x': Show cpu status" << std::endl;
             std::cout << "   'g': Show gpu status" << std::endl;
             std::cout << "   'h': Show general hadware status" << std::endl;
             std::cout << "   '+': Add breakpoint" << std::endl;
             std::cout << "   '-': List/Remove breakpoints" << std::endl;
             std::cout << "   'i': Inspect memory" << std::endl;
             std::cout << "   'l': List history" << std::endl;
             std::cout << "   'q': Quit program" << std::endl;
             std::cout << "   Enter: Step" << std::endl << std::endl;
             return run_repl();
         }
         default: return true;
     }
     
     return true;
 }
コード例 #10
0
ファイル: app.c プロジェクト: pasoev/guile-words
int main(int argc, char *argv[]){
  bool add_to_hist_flg = false;
  bool show_version_flg = false;
  bool print_hist_flg = false;
  char *action = NULL;

  int index;
  int c;

  opterr = 0;
  /* Get the action and the word from command line */

  while((c = getopt(argc, argv, "vhr")) != -1){
    switch(c){
    case 'h':
      add_to_hist_flg = true;
      break;
    case 'v':
      show_version_flg = true;
      break;
    case 'r':
      print_hist_flg = true;
      break;
    case '?':
      if(optopt == 'c'){
        fprintf(stderr,
                "Option -%c requires an argument.\n",
                optopt);
      }else if(isprint(optopt)){
        fprintf(stderr,
                "Unknown option `-%c'.\n",
                optopt);
      }else{
        fprintf(stderr,
                "Unknown option character `\\x%x'.\n",
                optopt);
      }

      return 1;

    default:
      print_usage();
      abort();
    }
  }

  if(show_version_flg){
    print_version();
    return EXIT_SUCCESS;
  }

  if(print_hist_flg){
    print_history(hist_fname);
  }

  init();

  /*
    Process the positional arguments: the first argument being the
    action and the remaining ones the words to look up.
  */
  int i = 0;
  for (index = optind; index < argc; index++){
    if(i == 0){
      /* The argument specifies the action, like antonym, synonym */
      action = argv[index];
    }else{
      process_phrase(action, argv[index], add_to_hist_flg);
    }
    
    i++;
  }

  return EXIT_SUCCESS;
}
コード例 #11
0
ファイル: simplesh.c プロジェクト: icyflame/os-lab
int main(int argc, char ** argv, char ** envp) {

	strcat(HISTFILENAME, getenv("HOME"));
	strcat(HISTFILENAME, "/histfile");

	printf("History file: %s\n", HISTFILENAME);

	char * tokens[100];
	int offset = 0;

	while(1) {

		getcw();
		printf("%s > ", cwd);
		fgets(command, COMMAND_SIZE, stdin);

		int n = strlen(command);

		if(n == 1) {
			continue;
		}

		if(command[n-1] == '\n'){
			command[n-1] = '\0';
			n = n - 1; // Found that n = strlen + 1.
		}

		write_cmd_to_file(command);

		printf("You entered %s %d\n", command, n);
		// split the string using the space character
		char temp_string[256];
		strcpy(temp_string, command);
		tokens[0] = (char *) malloc(TOKEN_SIZE * sizeof(char));
		strcpy(tokens[0], strtok(temp_string, " "));
		printf("Token 0: %s\n", tokens[0]);
		int num_tokens;
		for(num_tokens=1; ; ++num_tokens) {
			tokens[num_tokens] = (char *) malloc(TOKEN_SIZE * sizeof(char));
			tokens[num_tokens] = strtok(NULL, " ");
			if(tokens[num_tokens] == NULL)
				break;
		}

		if(strcmp(tokens[0], "exit") == 0) {
			return 0;
		} else if(strcmp(tokens[0], "clear") == 0) {
			printf("\033[2J\033[1;1H");
		} else if(strcmp(tokens[0], "env") == 0) {
			int i;
			for(i=0; envp[i]!=0;++i){
				printf("%s\n", envp[i]);
			}
		} else if(strcmp(tokens[0], "history") == 0) {
			print_history();
		} else if(strcmp(tokens[0], "pwd") == 0) {
			printf("%s\n", cwd);
		} else if(strcmp(tokens[0], "cd") == 0) {
			chdir(getenv("HOME"));
		} else if(strcmp(tokens[0], "ls") == 0) {
			DIR * pwd = opendir(".");
			if(pwd == NULL) {
				perror("mkdir encountered an error!");
			} else {
				struct dirent * dp;
				while((dp = readdir(pwd)) != NULL) {
					printf("%s\n", dp->d_name);
				}
			}
		}	else if(strcmp(tokens[0], "cd") == 0 && num_tokens >= 2) {
			chdir(tokens[1]);
		} else if(strcmp(tokens[0], "history") == 0) {
			int num_commands_to_display = atoi(tokens[1]);
			read_last_few_commands(num_commands_to_display);
		} else if(strcmp(tokens[0], "mkdir") == 0 && num_tokens >= 2) {
			if(mkdir(tokens[1], S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) {
				perror("mkdir failed");
			}
		} else if(strcmp(tokens[0], "rmdir") == 0 && num_tokens >= 2) {
			if(rmdir(tokens[1]) == -1) {
				perror("rmdir failed");
			}
		} else {
			execute(tokens, num_tokens);
		}
	}
	return 0;
}
コード例 #12
0
ファイル: mysh11.c プロジェクト: xwang322/Operating-System
// 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;        
}
コード例 #13
0
ファイル: shell.c プロジェクト: CptSpaceToaster/jash
int do_cmd(char *input, char *cwd, history_t history, FILE *in, FILE *out) {
    char *tokens[SIZE];
    char *trim;
    int len;
    int num_tokens;
    int pid;
    int backgnd = 0;

    // trim leading whitespace
    trim = input;
    while (*trim == ' ')
        trim++;

    len = strlen(trim);
    if (len == 1)
        return 0;

    // remove trailing newlines
    if (trim[len-1] == '\n')
        trim[len-1] = '\0';

    // check to see if the user is trying to replay history right away
    if (strncmp(trim, "!", 1) == 0) {
        if (replay_history(history, get_val(trim + sizeof(char)), input)) {
            fprintf(stderr, "Line '%s' not found\n", trim + sizeof(char));
            return 0;
        }
        return do_cmd(input, cwd, history, in, out);
    }

    // don't store history replay's in the history
    append_history(history, trim);

    // tokenize
    num_tokens = tokenize(trim, tokens);

    // built-ins
    // internal exit command
    if (!strncmp(tokens[0], "quit", 5) ||
        !strncmp(tokens[0], "exit", 5) ) {
        return EXIT_NORMAL;
    }

    // print working directory
    if (!strncmp(tokens[0], "pwd", 4)) {
        printf("%s\n", cwd);
        return 0;
    }

    // print all history
    if (!strncmp(tokens[0], "history", 8)) {
        print_history(history);
        return 0;
    }

    // print all jobs
    if (!strncmp(tokens[0], "jobs", 5)) {
        print_job_list();
        return 0;
    }

    // change to a directory
    if (strncmp(tokens[0], "cd", 2) == 0) {
        if (num_tokens > 2) {
            if (chdir(tokens[1])) {
                perror("No such file or directory");
            } else {
                // on success, reset cwd
                if (getcwd(cwd, sizeof(char) * SIZE) == NULL) {
                    perror("getcwd() error");
                    return 1;
                }
            }
        }
        return 0;
    }

    // do some token scraping for redirection
    if (check_for_specials(tokens, num_tokens, &in, &out, &backgnd))
        return 0;

    if ((pid = fork()) < 0) {
        perror("fork failure");
        return 1;
    } else if (pid == 0) {
        // allow inpout and output redirection
        if (in)
            dup2(fileno(in), STDIN_FILENO);
        if (out)
            dup2(fileno(out), STDOUT_FILENO);

        // kick off this wild ride
        if (execvp(tokens[0], tokens) < 0) {
            fprintf(stderr, "No command \'%s\' found\n", tokens[0]);
            exit(1);
        }
        // here be unreachable
    } else {
        // add job to list of running jobs
        len = add_job(pid, tokens);
        if (!backgnd) {
            while(last_corpse != pid);
            printf("Process returned: %d\n", last_corpse_status);
        } else {
            printf("[%d] %d\n", len, pid);
        }
        return 0;
    }

    // The compiler doesn't see the exec, and thinks a
    // child could make it here
    fprintf(stderr, "Warning: child escaped!\n");
    return 0;
}
コード例 #14
0
ファイル: main.c プロジェクト: TolikT/pa3
int main(int argc, char *argv[]){
	
	// create an IO structure
	IO *inout = (IO*)malloc(sizeof(IO));
	
	// number of child processes from command line to numOfChildren variable
	int opt;	
	while ( (opt = getopt(argc,argv,"p:")) != -1){
		switch (opt){
		case 'p': 
			inout -> numOfChildren = atoi(optarg);
			break;
		default:
			free(inout); 
			return -1;		
        	}
	}

	inout -> id = PARENT_ID;
	
	// create or open logs for writing
	FILE *pipesLog = fopen(pipes_log, "w+");
	FILE *eventsLog = fopen(events_log, "w+");
	
	// create pipes and fill the inout.pipes  
	for (int i = 0; i < inout -> numOfChildren + 1; i++){
		for (int j = 0; j < inout -> numOfChildren + 1; j++){
			if  (i != j){
				Pipe *pipeMem = (Pipe*)malloc(sizeof(Pipe));
				int pipefd[2];
				pipe(pipefd);
				fcntl(pipefd[0], F_SETFL, O_NONBLOCK);
				fcntl(pipefd[1], F_SETFL, O_NONBLOCK);
				pipeMem -> in = pipefd[0];
				pipeMem -> out = pipefd[1];
				inout -> pipes[i][j] = pipeMem;
				fprintf(pipesLog, log_opened_fmt, pipefd[0], pipefd[1]);
				fflush(pipesLog);
				printf(log_opened_fmt, pipefd[0], pipefd[1]);
			}
		}	
	}	
	
	Message *msgReceive = (Message*)malloc(sizeof(Message));
	BalanceHistory *balanceHistory = (BalanceHistory*)malloc(sizeof(BalanceHistory));
	AllHistory *allHistory = (AllHistory*)malloc(sizeof(AllHistory));

	// create children
	for (int id = 1; id < inout -> numOfChildren + 1; id++){
		switch(fork()){
			case -1:
				perror("fork");
				exit(EXIT_FAILURE);
			case 0:
				lamport_process_init();
				fprintf(eventsLog, log_started_fmt, get_lamport_time(), id, getpid(), getppid(), atoi(argv[optind+id-1]));
				fflush(eventsLog);
				printf(log_started_fmt, get_lamport_time(), id, getpid(), getppid(), atoi(argv[optind+id-1]));
				timestamp_t after;
				balanceHistory -> s_id = id;
				balanceHistory -> s_history_len = 1;
				balanceHistory -> s_history[0].s_balance = atoi(argv[optind+id-1]);
				balanceHistory -> s_history[0].s_time = get_lamport_time();
				balanceHistory -> s_history[0].s_balance_pending_in = 0;
				
				inout -> id = id;
				
				// close unused pipes
				for (int i = 0; i < inout -> numOfChildren + 1; i++){
					for (int j = 0; j < inout -> numOfChildren + 1; j++){					
						if (i != j){
							if (i != inout -> id && j != inout -> id){
								close(inout -> pipes[i][j] -> in);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								close(inout -> pipes[i][j] -> out);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
							}
							if (i == inout -> id){
								close(inout -> pipes[i][j] -> in);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
							}
							if (j == inout -> id){
								close(inout -> pipes[i][j] -> out);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
							}
							
						}
					
					}
				}
				
				// update localTime 
				lamport_before_send();

				// fill the STARTED message								
				Message *msg = (Message*)malloc(sizeof(Message));
				sprintf(msg -> s_payload, log_started_fmt, get_lamport_time(), id, getpid(), getppid(), balanceHistory -> s_history[balanceHistory -> s_history_len].s_balance);
				msg -> s_header.s_magic = MESSAGE_MAGIC;
				msg -> s_header.s_payload_len = strlen(msg -> s_payload)+1;
				msg -> s_header.s_type = STARTED;
				msg -> s_header.s_local_time = get_lamport_time();

				// send STARTED message to other processes
				send_multicast(inout, msg);

				// receive STARTED message from other processes
				for (int i = 1; i < inout -> numOfChildren + 1; i++){
					if (i != inout -> id){					
						do{
							while (receive(inout, i, msgReceive) == -1)
								usleep(1000);
							// update localTime
							lamport_after_receive(&msgReceive -> s_header);
						} while (msgReceive -> s_header.s_type != STARTED);
					}
				}

				// logs
				fprintf(eventsLog, log_received_all_started_fmt, get_lamport_time(), inout -> id);
				fflush(eventsLog);
				printf(log_received_all_started_fmt, get_lamport_time(), inout -> id);
				
				// useful work
				while(1){
					int src = receive_any(inout, msgReceive);

					// update localTime
					lamport_after_receive(&msgReceive -> s_header);

					if (msgReceive -> s_header.s_type==STOP) break;
					printf("%d RECEIVE FROM %d TYPE %d\n", inout ->id, src, msgReceive -> s_header.s_type);
					TransferOrder *transferOrder;
					switch(msgReceive -> s_header.s_type){
						case TRANSFER:
							transferOrder =  (TransferOrder*)msgReceive -> s_payload;
							if (src == 0){
								after = get_lamport_time()+1;
								for (int i = balanceHistory -> s_history_len; i <= after; i++){
									balanceHistory -> s_history[i] = balanceHistory -> s_history[i-1];
									balanceHistory -> s_history[i].s_time = balanceHistory -> s_history[i-1].s_time+1;								
									balanceHistory -> s_history[i].s_balance_pending_in = 0;	
									balanceHistory -> s_history_len ++;
								}								
								balanceHistory -> s_history[after].s_balance -= transferOrder -> s_amount;							
								balanceHistory -> s_history[after].s_balance_pending_in = transferOrder -> s_amount;							
								
								// update localTime 
								lamport_before_send();
								msgReceive -> s_header.s_local_time = get_lamport_time();
								send(inout, transferOrder -> s_dst, msgReceive);
								fprintf(eventsLog, log_transfer_out_fmt, get_lamport_time(), inout -> id, transferOrder -> s_amount, transferOrder -> s_dst);
								fflush(eventsLog);
								printf(log_transfer_out_fmt, get_lamport_time(), inout -> id, transferOrder -> s_amount, transferOrder -> s_dst);								
							}
							if (src > 0){
								after = get_lamport_time();
								for (int i = balanceHistory -> s_history_len; i<=after; i++){
									balanceHistory -> s_history[i] = balanceHistory -> s_history[i-1];
									balanceHistory -> s_history[i].s_time=balanceHistory -> s_history[i-1].s_time+1;								
									balanceHistory -> s_history[i].s_balance_pending_in = 0;
									balanceHistory -> s_history_len ++;	
								}								
								balanceHistory -> s_history[after].s_balance += transferOrder -> s_amount;
								balanceHistory -> s_history[after].s_balance_pending_in = 0;

								// update localTime 
								lamport_before_send();

								msg -> s_header.s_magic = MESSAGE_MAGIC;
								msg -> s_header.s_payload_len = 0;
								msg -> s_header.s_type = ACK;
								msg -> s_header.s_local_time = get_lamport_time();
								send(inout, PARENT_ID, msg);
								fprintf(eventsLog, log_transfer_in_fmt, get_lamport_time(), inout -> id, transferOrder -> s_amount, transferOrder -> s_dst);
								fflush(eventsLog);
								printf(log_transfer_in_fmt, get_lamport_time(), inout -> id, transferOrder -> s_amount, transferOrder -> s_src);								
							}						
					}
				}

				// update localTime 
				lamport_before_send();

				// fill the DONE message
				sprintf(msg -> s_payload, log_done_fmt, get_lamport_time(), inout -> id, balanceHistory -> s_history[balanceHistory -> s_history_len-1].s_balance);
				msg -> s_header.s_magic = MESSAGE_MAGIC;
				msg -> s_header.s_payload_len = strlen(msg -> s_payload)+1;
				msg -> s_header.s_type = DONE;
				msg -> s_header.s_local_time = get_lamport_time();

				// send DONE message to other processes
				send_multicast(inout, msg);

				// receive DONE message from other processes
				for (int i = 1; i < inout -> numOfChildren + 1; i++){
					if (i != inout -> id){					
						do{
							while (receive(inout, i, msgReceive) == -1)
								usleep(1000);
							// update localTime
							lamport_after_receive(&msgReceive -> s_header);
						} while (msgReceive -> s_header.s_type != DONE);
					}
				}				

				// logs
				fprintf(eventsLog, log_received_all_done_fmt, get_lamport_time(), inout -> id);
				fflush(eventsLog);
				printf(log_received_all_done_fmt, get_lamport_time(), inout -> id);

				// update localTime 
				lamport_before_send();
				
				// fill the BALANCE_HISTORY message
				msg -> s_header.s_magic = MESSAGE_MAGIC;
				msg -> s_header.s_payload_len = sizeof(BalanceHistory);
				msg -> s_header.s_type = BALANCE_HISTORY;
				msg -> s_header.s_local_time = get_lamport_time();

							
				if (msg -> s_header.s_local_time > after){
					for (int i = balanceHistory -> s_history_len; i<=msg -> s_header.s_local_time; i++){
						balanceHistory -> s_history[i] = balanceHistory -> s_history[i-1];
						balanceHistory -> s_history[i].s_time=balanceHistory -> s_history[i-1].s_time+1;
						balanceHistory -> s_history[i].s_balance_pending_in = 0;
						balanceHistory -> s_history_len ++;
					}
				}

				memcpy(msg -> s_payload, balanceHistory, msg -> s_header.s_payload_len);
			

				// send the BALANCE_HISTORY to each child	
				send(inout, PARENT_ID, msg);
				
				// close all other pipes 
				for (int i = 0; i < inout -> numOfChildren + 1; i++){
					for (int j = 0; j < inout -> numOfChildren + 1; j++){					
						if (i != j){
							if (i == inout -> id){
 								close(inout -> pipes[i][j] -> out);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
							}
							if (j == inout -> id){
 								close(inout -> pipes[i][j] -> in);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								
							}
						}
					}
				}
				
				for (int i = 0; i < inout -> numOfChildren + 1; i++){
					for (int j = 0; j < inout -> numOfChildren + 1; j++){					
						if (i != j) free(inout -> pipes[i][j]);
 					}						
				}
				free(msg);

				fprintf(eventsLog, log_done_fmt, get_lamport_time(), inout -> id, balanceHistory -> s_history[balanceHistory -> s_history_len-1].s_balance);
				fflush(eventsLog);
				printf(log_done_fmt, get_lamport_time(), inout -> id, balanceHistory ->s_history[balanceHistory -> s_history_len-1].s_balance);
				return 0;
			default:
				break;				
		}
	}
	
	for (int i = 0; i < inout -> numOfChildren + 1; i++){
		for (int j = 0; j < inout -> numOfChildren + 1; j++){					
			if (i != j){
				if (i != PARENT_ID && j != PARENT_ID){
 					close(inout -> pipes[i][j] -> in);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
					close(inout -> pipes[i][j] -> out);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
				}
				if (i == PARENT_ID){
					close(inout -> pipes[i][j] -> in);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
				}
				if (j == PARENT_ID){
					close(inout -> pipes[i][j] -> out);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
				}
			}
		}
	}

	for (int i = 1; i < inout -> numOfChildren + 1; i++){
		if (i != inout -> id){		
			do{
				while (receive(inout, i, msgReceive) == -1)
					usleep(1000);
				// update localTime
				lamport_after_receive(&msgReceive -> s_header);
				
			} while (msgReceive -> s_header.s_type != STARTED);
		}
	}

	fprintf(eventsLog, log_received_all_started_fmt, get_lamport_time(), inout -> id);
	fflush(eventsLog);
	printf(log_received_all_started_fmt, get_lamport_time(), inout -> id);
	
	// for pa2
	bank_robbery(inout, inout -> numOfChildren);
	
	Message *msg = (Message*)malloc(sizeof(Message));
	
	// update localTime 
	lamport_before_send();

	// fill the STOP message
	msg -> s_header.s_magic = MESSAGE_MAGIC;
	msg -> s_header.s_payload_len = 0;
	msg -> s_header.s_type = STOP;
	msg -> s_header.s_local_time = get_lamport_time();

	// send the STOP to each child	
	send_multicast(inout, msg);
	
	// receive all DONE messages
	for (int i = 1; i < inout -> numOfChildren + 1; i++){
		do{
			while (receive(inout, i, msgReceive) == -1)
				usleep(1000);
			// update localTime
			lamport_after_receive(&msgReceive -> s_header);

		} while (msgReceive -> s_header.s_type != DONE);
	}

	//logs
	fprintf(eventsLog, log_received_all_done_fmt, get_lamport_time(), inout -> id);
	fflush(eventsLog);
	printf(log_received_all_done_fmt, get_lamport_time(), inout -> id);
	
	// receive all BALANCE_HISTORY messages and fill AllHistory
	allHistory -> s_history_len = inout -> numOfChildren;
	for (int i = 1; i < inout -> numOfChildren + 1; i++){
		do{
			while (receive(inout, i, msgReceive) == -1)
				usleep(1000);
			// update localTime
			lamport_after_receive(&msgReceive -> s_header);
		} while (msgReceive -> s_header.s_type != BALANCE_HISTORY);		
		
		memcpy(&allHistory -> s_history[i-1], msgReceive -> s_payload, sizeof(BalanceHistory));
	}
	
	for (int i = 0; i < inout -> numOfChildren + 1; i++){
		for (int j = 0; j < inout -> numOfChildren + 1; j++){					
			if (i != j){
				if (i == PARENT_ID){
 					close(inout -> pipes[i][j] -> out);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
				}
				if (j == PARENT_ID){
 					close(inout -> pipes[i][j] -> in);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
				}
			}
		}
	}
	for (int i = 0; i < inout -> numOfChildren; i++)
		wait(NULL);
	for (int i = 0; i< inout -> numOfChildren; i++){
		for (int j = 0; j<=allHistory -> s_history[i].s_history_len; j++){
			printf("N: %d process: %d balance: %d time: %d\n", j, allHistory -> s_history[i].s_id, allHistory -> s_history[i].s_history[j].s_balance, allHistory -> s_history[i].s_history[j].s_time);		
		}
	}
	print_history(allHistory);
	free(inout);
	free(msg);
	free(msgReceive);
	free(balanceHistory);
	free(allHistory);
	fclose(pipesLog);
	fclose(eventsLog);	
	return 0;
}
コード例 #15
0
ファイル: shell.c プロジェクト: vaot/various
int handle_inline_commands(char *tokens[], char *bufCopy, char *buff, _Bool *in_bg) {
  int reply = 0;

  if (strcmp(tokens[0], "exit") == 0) {
    reply = 1;
    free(bufCopy);
    exit(0);
  } else if (strcmp(tokens[0], "cd") == 0) {
    chdir(tokens[1]);
    add_to_history(bufCopy);
    reply = 1;

  } else if (strcmp(tokens[0], "pwd") == 0) {
    char dir[COMMAND_LENGTH];
    getcwd(dir, sizeof(dir));
    dir[strlen(dir)] = '\0';

    write(STDOUT_FILENO, dir, strlen(dir));
    write(STDOUT_FILENO, "\n", strlen("\n"));
    add_to_history(bufCopy);
    reply = 1;

  } else if (strcmp(tokens[0], "history") == 0) {
    add_to_history(bufCopy);
    print_history();
    reply = 1;

  } else if (strcmp(tokens[0], "!!") == 0) {
    if (commandCounter <= 0) {
      printf("SHELL: Unknown history command.\n");
      free(bufCopy);
      reply = -1;
    } else {
      retokenize_cmd(commandCursor-1, tokens, bufCopy, buff, in_bg);
      printf("%s\n", bufCopy);

      // Recurse, in case the command is to be handled
      // inline.
      reply = handle_inline_commands(tokens, bufCopy, buff, in_bg);
    }

  } else if (tokens[0][0] == '!') {
    int count = strlen(tokens[0]);

    for (int i = 0; i < count-1; ++i) tokens[0][i] = tokens[0][i+1];
    tokens[0][count-1] = '\0';

    int cmdNumber = atoi(tokens[0]);

    if (cmdNumber > commandCounter) {
      printf("SHELL: Unknown history command.\n");
      free(bufCopy);
      reply = -1;

    } else if (cmdNumber == 0) {
      printf("SHELL: Unknown history command.\n");
      free(bufCopy);
      reply = -1;

    } else {
      int cmdPosition = cmd_number_to_position(cmdNumber);
      retokenize_cmd(cmdPosition, tokens, bufCopy, buff, in_bg);
      printf("%s\n", bufCopy);

      // Recurse, in case the command is to be handled
      // inline.
      reply = handle_inline_commands(tokens, bufCopy, buff, in_bg);
    }


  } else if ((int)(*tokens[0]) == EM_VALUE) {
    free(bufCopy);
    reply = -1;

  /* Handle when they type a bunch of spaces and hit enter */
  } else if (strlen(*tokens) == 0) {
    free(bufCopy);
    reply = -1;

  } else {
    reply = 0;
  }

  return reply;
}
コード例 #16
0
ファイル: shell.c プロジェクト: vaot/various
void handle_SIGINT(int st) {
  printf("\n");
  print_history();
}
コード例 #17
0
ファイル: chat_client.c プロジェクト: sshamilton/chatservice
static	void	User_command()
{
	char	command[130];
	char	mtext[80];
	char	mess[MAX_MESSLEN];
	char	group[80];
	char	groups[10][MAX_GROUP_NAME];
	int	num_groups;
	unsigned int	mess_len;
	int	ret;
	int	i;
	int 	like;
	sp_time test_timeout;
	char    server_id[1];

	for( i=0; i < sizeof(command); i++ ) command[i] = 0;
	if( fgets( command, 130, stdin ) == NULL ) 
            Bye();
	/* remove newline from string */
	command[strlen(command) -1] = 0;
	switch( command[0] )
	{
		case 'j':
			ret = sscanf( &command[2], "%s", group );
			if (connected > 0) {
 			   if( ret < 1 ) 
			   {
				printf(" invalid chatroom \n> ");
				break;
			  } 
			  join_room(group);
			}
			else {printf("You must connect to a server first\n>"); }
			break;
                case 'c':
			ret = sscanf( &command[2], "%s", group );
                        if( ret < 1 )
                        {
                                printf(" invalid server id \n> ");
                                break;
                        }
		  	join_server(group);
                        break;
  		case 'q':
			Bye();
			exit(0);
			break;
  		case '?':
			show_menu();
			break;
   		case 'u':
			if (connected > 0 ) {
			  ret = sscanf( &command[2], "%s", username);
			  if( ret < 1 )
			  {
				printf(" Invalid Username\n> ");
				break;
			  }
			  else
			  {
				printf("Username set to %s\n> ", username);
				/*If in chatroom, disconnect */
				if (strlen(chatroom) > 0)
  				{
        				sprintf(chatroom, "%s%d",chatroom, connected);
        				printf("leaving chatroom, %s due to username change\n", chatroom);
        				SP_leave(Mbox, chatroom);
  				} 
			  }
			}
			else {printf("You must connect to a server first\n>"); }

			break;
 		case 'a':
			if (connected > 0) {
			  strncpy(mtext, &command[2], 130);
			  if( strlen(mtext) < 1)
			  {
				printf(" invalid message\n> ");
				break;
			  }
			  send_msg(mtext);
			}

			else {printf("You must connect to a server first\n>"); }

			break;
		case 'l':
			if (connected > 0) {
			  ret = sscanf( &command[2], "%d", &like  );
                          if( ret < 1)
                          {
                                printf(" invalid line\n> ");
                                break;
                          }
                          like_msg(like, 1);
			}
			else {printf("You must connect to a server first\n>"); }

			break;
		case 'r':
			if (connected > 0) {
			  ret = sscanf( &command[2], "%d", &like);
			  if (ret < 1)
			  {
				printf(" invalid line\n> ");
				break;
			  }
			  like_msg(like, 0);
			}
			else {printf("You must connect to a server first\n>"); }

			break;
		case 'h':
			if (strlen(chatroom) != 0) {
			   print_history();
    			   printf("> ");
			}
			else printf("You are not in a chatroom.\n>");
			break;
		case 'v':
			if (connected > 0) {
				show_servers();
			}
			else {printf("You must connect to a server first\n>"); }
			break;
		default: 
			printf("> ");
			break;
    }
   fflush(stdout); 
}
コード例 #18
0
ファイル: infotzup.c プロジェクト: Makoto-Sasahara/opentoonz
void main(int argc, char *argv[]) {
  char outname[512], inname[512], *boh;
  int len, i, j, total;
  IMAGE *img = NIL, *newimg = 0;
  struct cmap_color *cmap;
  struct gl_color *gl_buffer;

  toonz_init(DUMMY_KEY_SLOT, (int *)&argc, argv);
  InibisciDongle();
  unprotect_lib();

  if (argc < 2) {
    printf("### %s error: missing argument\n", argv[0]);
    printf(" usage: %s infile \n", argv[0]);
    exit(0);
  }

  if (*argv[1] == '-') {
    printf("bad filename <%s> \n", argv[1]);
    exit(0);
  }

  printf("\n\n");

  for (i = 1; i < argc; i++) {
    strcpy(inname, argv[i]);

    len = strlen(inname);
    if (len < 4 || (STR_NE(inname + len - 4, ".tzu") &&
                    STR_NE(inname + len - 4, ".tzp"))) {
      printf("### %s error: file %s is not tz(up)\n", argv[0], inname);
      continue;
    }

    /*   printf(">> Loading %s\n", inname); */

    img = img_read_tzup_info(inname);
    if (!img) {
      printf("### %s error: file %s not found\n", argv[0], inname);
      continue;
    }

    printf(" > IMAGE: %s \n\n", inname);
    printf("   > Dimension:    xsize=%d\t\tysize=%d\n", img->pixmap.xsize,
           img->pixmap.ysize);
    printf("   > Savebox:\n");
    printf("   >   Start       x0=%d\t\ty0=%d \n", img->pixmap.xD,
           img->pixmap.yD);
    printf("   >   Dimensions  xsize=%d\t\tysize=%d \n", img->pixmap.xSBsize,
           img->pixmap.ySBsize);
    printf("   > Resolution:   x_dpi=%g\ty_dpi=%g \n", img->pixmap.x_dpi,
           img->pixmap.y_dpi);
    printf("   > H-position (pixels): %g \n", img->pixmap.h_pos);

    printf("\n");
    if (img->history) print_history(img->history);

    printf("\n\n");
    free_img(img);
    img = NIL;
  }

  printf(" Bye!!\n");
}