int main(int argc, char *argv[]) { DCL_THREADGBL_ACCESS; GTM_THREADGBL_INIT; set_blocksig(); gtm_imagetype_init(DSE_IMAGE); gtm_wcswidth_fnptr = gtm_wcswidth; gtm_env_init(); /* read in all environment variables */ licensed = TRUE; TREF(transform) = TRUE; op_open_ptr = op_open; patch_curr_blk = get_dir_root(); err_init(util_base_ch); GTM_ICU_INIT_IF_NEEDED; /* Note: should be invoked after err_init (since it may error out) and before CLI parsing */ sig_init(generic_signal_handler, dse_ctrlc_handler, suspsigs_handler); atexit(util_exit_handler); SET_LATCH_GLOBAL(&defer_latch, LOCK_AVAILABLE); get_page_size(); stp_init(STP_INITSIZE); rts_stringpool = stringpool; getjobname(); INVOKE_INIT_SECSHR_ADDRS; getzdir(); prealloc_gt_timers(); initialize_pattern_table(); gvinit(); region_init(FALSE); INIT_GBL_ROOT(); /* Needed for GVT initialization */ getjobnum(); util_out_print("!/File !_!AD", TRUE, DB_LEN_STR(gv_cur_region)); util_out_print("Region!_!AD!/", TRUE, REG_LEN_STR(gv_cur_region)); cli_lex_setup(argc, argv); CREATE_DUMMY_GBLDIR(gd_header, original_header, gv_cur_region, gd_map, gd_map_top); gtm_chk_dist(argv[0]); # ifdef DEBUG if ((gtm_white_box_test_case_enabled && (WBTEST_SEMTOOLONG_STACK_TRACE == gtm_white_box_test_case_number) )) { sgmnt_addrs * csa; node_local_ptr_t cnl; csa = &FILE_INFO(gv_cur_region)->s_addrs; cnl = csa->nl; cnl->wbox_test_seq_num = 1; /*Signal the first step and wait here*/ while (2 != cnl->wbox_test_seq_num) /*Wait for another process to get hold of the semaphore and signal next step*/ LONG_SLEEP(10); } # endif if (argc < 2) display_prompt(); io_init(TRUE); while (1) { if (!dse_process(argc)) break; display_prompt(); } dse_exit(); REVERT; }
int main(int argc, char **argv) { display_prompt(); FILE *datafile = NULL; datafile = fopen("shell-config", "r"); Node *head = NULL; if (datafile != NULL) { char line[1024]; while (fgets(line, 1024, datafile) != NULL) { int slen = strlen(line); line[slen-1] = '\0'; list_append(line, "", &head); } fclose(datafile); } char curr_mode = 's'; char buffer[1024]; Node *paused_list = NULL; Node *cpidlist = NULL; while (fgets(buffer, 1024, stdin) != NULL) { char *newbuffer = replace_pound(buffer); newbuffer[strlen(newbuffer)-1] = '\0'; char **pointers_to_commands = tokenify(newbuffer, ";"); free(newbuffer); if (pointers_to_commands[0] == NULL) { display_prompt(); continue; } if (curr_mode == 's') { curr_mode = sequential_mode(pointers_to_commands, head); } else if (curr_mode == 'p') { curr_mode = parallel_mode(pointers_to_commands, head, &paused_list, &cpidlist); } if (curr_mode == 'e') { free_tokens(pointers_to_commands); list_clear(paused_list); list_clear(cpidlist); list_clear(head); exit(0); } display_prompt(); free_tokens(pointers_to_commands); } list_clear(head); list_clear(paused_list); list_clear(cpidlist); printf("\n"); return 0; }
/* ** If termcaps database isn't reachable: ** => returns fget_next_line (normal get_next_line). ** Else => returns tc_get_next_line (using termcaps). */ char *get_next_line(int fd, char **env) { static char *line = NULL; char *str; int i; i = 0; if ((i = init_termios(env)) == 1) return (fget_next_line(fd)); if (i == -1) return (NULL); if ((str = line) != NULL) line = NULL; else if ((str = tc_get_next_line(fd, env)) != NULL) my_putchar('\n'); while (str && str[i] && str[i] != ';') jump_inhibitors(str, &i); if (str && str[i]) if (display_prompt(0, 0, 1) || (line = my_strdup(str + i + 1)) == NULL || (str = my_xstrndup(str, i)) == NULL) return (NULL); if (init_termios(NULL)) return (NULL); return (str); }
int shell(t_config *conf) { int ret; char *cmd; ret = EXIT_SUCCESS; while (1) { check_status(conf); if (check_fd_read(0) == -1) display_prompt(conf); if (read_cmdline(conf) == MYSH_SIGNAL_EXIT) { ret = EXIT_SUCCESS; break; } if ((cmd = commandline_rewrite(conf->cmdline.buffer)) == NULL) continue ; if (my_exec(conf, cmd, &ret) == MYSH_SIGNAL_EXIT) break; } my_putchar('\n'); return (ret); }
void print_line(t_edited_line *line) { char *letter; t_atom *tmp_curr; tputs(tgetstr("cd", NULL), 1, ft_outc); display_prompt(line->option->prompt); tmp_curr = line->data->curr; line->data->curr = NULL; while ((letter = ft_lst_next_content(line->data))) { if (*letter != ' ') ft_putchar(*letter); else ft_putchar(' '); } ft_lst_prev_content(line->data); calcul_info(line); line->data->curr = tmp_curr; if (!line->info->curr_mod && tmp_curr == line->data->last) { tputs(tgetstr("do", NULL), 1, ft_outc); tputs(tgetstr("cr", NULL), 1, ft_outc); } }
int main (int argc, char **argv) { int res; DCL_THREADGBL_ACCESS; GTM_THREADGBL_INIT; set_blocksig(); gtm_imagetype_init(MUPIP_IMAGE); invocation_mode = MUMPS_UTILTRIGR; gtm_wcswidth_fnptr = gtm_wcswidth; gtm_env_init(); /* read in all environment variables */ err_init(util_base_ch); UNICODE_ONLY(gtm_strToTitle_ptr = >m_strToTitle); GTM_ICU_INIT_IF_NEEDED; /* Note: should be invoked after err_init (since it may error out) and before CLI parsing */ sig_init(generic_signal_handler, NULL, suspsigs_handler, continue_handler); /* Note: no ^C handler is defined (yet) */ atexit(mupip_exit_handler); licensed = TRUE; in_backup = FALSE; op_open_ptr = mu_op_open; mu_get_term_characterstics(); cli_lex_setup(argc,argv); if (argc < 2) /* Interactive mode */ display_prompt(); /* this call should be after cli_lex_setup() due to S390 A/E conversion */ gtm_chk_dist(argv[0]); INIT_GBL_ROOT(); /* Needed for GVT initialization */ init_gtm(); while (TRUE) { func = 0; if ((res = parse_cmd()) == EOF) break; else if (res) { if (1 < argc) rts_error(VARLSTCNT(4) res, 2, LEN_AND_STR(cli_err_str)); else gtm_putmsg(VARLSTCNT(4) res, 2, LEN_AND_STR(cli_err_str)); } if (func) func(); if (argc > 1) /* Non-interactive mode, exit after command */ break; display_prompt(); } mupip_exit(SS_NORMAL); }
void crash_handler(int sig) { printf("\n"); if (sig == SIGINT || sig == SIGCONT) display_prompt(f_all(NULL)); else exit(0); }
int key_enterr(t_link *link) { if (link->line != NULL) { my_putchar('\n'); get_command_line(link, convert_list_to_str(link->line), 1); link->line = NULL; if (link->exit_status == 0 && link->term_caps == 1) display_prompt(link); } else { my_putchar('\n'); display_prompt(link); } sauv_cur(); return (TRUE); }
/* ** If a SIGINT is received, it will kill current process. ** If no current process is executing, it will re-display prompt. */ void my_sigint(int signal) { if (signal == SIGINT) if (save_pid(0, 3) == NULL + 2) { my_putstr("^C\n"); display_prompt(0, 0, 0); } }
void run_cmdline_loop(repl_t *repl, JSContextRef ctx) { while (true) { char *input_line = NULL; if (config.dumb_terminal) { display_prompt(repl->current_prompt); input_line = get_input(); if (input_line == NULL) { // Ctrl-D pressed printf("\n"); break; } } else { // Handle prints while processing linenoise input if (cljs_engine_ready) { cljs_set_print_sender(ctx, &linenoisePrintNow); } // If *print-newline* is off, we need to emit a newline now, otherwise // the linenoise prompt and line editing will overwrite any printed // output on the current line. if (cljs_engine_ready && !cljs_print_newline(ctx)) { fprintf(stdout, "\n"); } char *line = linenoise(repl->current_prompt, prompt_ansi_code_for_theme(config.theme), repl->indent_space_count); // Reset printing handler back if (cljs_engine_ready) { cljs_set_print_sender(ctx, NULL); } repl->indent_space_count = 0; if (line == NULL) { if (errno == EAGAIN) { // Ctrl-C errno = 0; repl->input = NULL; empty_previous_lines(repl); repl->current_prompt = form_prompt(repl->current_ns, false); printf("\n"); continue; } else { // Ctrl-D exit_value = EXIT_SUCCESS_INTERNAL; break; } } input_line = line; } bool break_out = process_line(repl, ctx, input_line); if (break_out) { break; } } }
int main(int argc, char **argv, char **env) { (void)argc; (void)argv; t_env e; fill_struct(&e, env); display_prompt(&e); return (0); }
void sh_show_prompt() { display_prompt(); char buf[MAX_ARGS]; //type_block blockTest; //printf("size of struct %d, mem:%u, size_add:%u, next_add:%u, prev_add:%u, free_add:%u, data:%u\n",sizeof(struct block), blockTest, blockTest->size, blockTest->next, blockTest->prev, blockTest->free, blockTest + 1); while (1) { gets(buf, sizeof(buf)); trim(buf); if (strlen(buf) > 0) { sc_set_format(LIGHT_GREY); sh_do_command(buf); sh_clean_buffer(buf); display_prompt(); } } }
int main(int ac, char **av) { t_all all; if (ac != 3) return (usage(CLIENT)); init_all(&all, av[1], atoi(av[2])); printf("Connected to %s:%s\n", av[1], av[2]); display_prompt(); main_loop(all.sock, all.handlers); printf("Bye bye...\n"); close(all.sock); return (0); }
static bool lke_process(int argc) { bool flag = FALSE; int res; static int save_stderr = SYS_STDERR; ESTABLISH_RET(util_ch, TRUE); if (util_interrupt) rts_error(VARLSTCNT(1) ERR_CTRLC); if (SYS_STDERR != save_stderr) /* necesary in case of rts_error */ close_fileio(&save_stderr); assert(SYS_STDERR == save_stderr); func = 0; util_interrupt = 0; if (argc < 2) display_prompt(); if ( EOF == (res = parse_cmd())) { if (util_interrupt) { rts_error(VARLSTCNT(1) ERR_CTRLC); REVERT; return TRUE; } else { REVERT; return FALSE; } } else if (res) { if (1 < argc) { REVERT; rts_error(VARLSTCNT(4) res, 2, LEN_AND_STR(cli_err_str)); } else gtm_putmsg(VARLSTCNT(4) res, 2, LEN_AND_STR(cli_err_str)); } if (func) { flag = open_fileio(&save_stderr); /* save_stderr = SYS_STDERR if -output option not present */ func(); if (flag) close_fileio(&save_stderr); assert(SYS_STDERR == save_stderr); } REVERT; return(1 >= argc); }
void restart_prompt(int sig) { t_env *env; (void)sig; env = get_t_env(NULL); ft_putchar_fd('\n', get_fd(-1)); display_prompt(env); clear_line(get_first_line(env->le.line)); env->le.line = ft_memalloc(sizeof(t_line)); env->le.line->is_orig = 1; history(RES_ORI, NULL); env->le.pos_x = 4; }
int main (int argc, char **argv) { char user_input[USER_INPUT_BUFFER_MAX]; proper_exec_name (argv[0]); greet (); while (true) { display_prompt (); grab_input (user_input); process_input (user_input); } return EXIT_SUCCESS; }
void my_display(char **array, char *tmp, t_env_var *env) { int i; i = 0; write(1, "\n", 1); while (array != NULL && array[i]) { write(1, array[i], strlen(array[i])); write(1, "\t", 1); i++; } write(1, "\b \b\n", 4); display_prompt(env->env); write(1, tmp, strlen(tmp)); }
void main_loop(int sock, t_cmd_handler *handlers) { t_request req; int index; int r; while (get_next_line(2, &req.buf) != 0) { req.args = ft_strsplit(req.buf, ' '); index = get_index_handler(handlers, req.args[0]); if (index != -1) r = handlers[index].f(&req, sock); else printf("[%s] : Command not found\n", req.args[0]); ft_2dchardel(&req.args); free(req.buf); display_prompt(); } }
int main( int argc, char **argv ) { int input; display_prompt(); input = receive_input(); printf("%d\n", input); make_input_file("./datafiles"); //read_input_files("./inputfile.txt"); //print_matrix("./inputfile.txt"); //hashtable_s *hashtable = create_table(1); //insert(hashtable, "key1", "word"); //insert(hashtable, "key2", "noideawhatimdoing"); //insert(hashtable, "key3", "word"); //printf("%s\n%s\n%s\n", get(hashtable, "key1"), get(hashtable, "key2"), get(hashtable, "key3")); return 0; }
void run(void) { READ_STATUS s; char *cmdLine; while (1) { // print command line display_prompt(); // read input from command line s = readInput(stdin, &cmdLine); if (s == INPUT_READ_EOF) { free(cmdLine); exit(0); } if (s == INPUT_READ_OK) { run_cmd(cmdLine, INTERACTIVE_MODE); } } }
int main(void) { char *line; extern char **environ; char *tok; line = NULL; tok = NULL; (void)environ; while (42) { display_prompt(); line = get_command(); tok = ft_strtok(line, ';'); while (tok) { exec_command(environ, tok); tok = ft_strtok(NULL, ';'); } free(line); } return (0); }
/* _____________________________________________________ */ int main() { int argc; // Nombre d'arguments. char argl[MAXLIN]; // Ligne de commande "brute". char* argv[MAXVEC]; // Tableau d'arguments. // On désactive le buffer de 'stdout'. // (Sinon il faudrait parfois utiliser 'fflush'.) setvbuf(stdout, NULL, _IONBF, 0); status = 0; // Boucle infinie pouvant être interrompue par 'exit'. while (1) { // On affiche l'invite de commande. display_prompt(); // On récupère la commande de l'utilisateur. read_command(argl); // On découpe cette commande en arguments. argc = tokenize_command(argl, argv); // On met à jour le tableau de jobs. refresh_job_table(); // On essaye d'exécuter la commande, // et on stocke la valeur de retour. status = execute_command(argc, argv); } }
/** * Main */ int main(int argc, char* argv[], char* envp[]) { LOG_ENTRY; parse_args(argc, argv); input_buffer = calloc(INPUT_BUFFER_SIZE, sizeof(char)); prompt_buffer = calloc(PROMPT_BUFFER_SIZE, sizeof(char)); while(1) { display_prompt(); if(read_input() != NULL) { bool valid = handle_input(); if (valid) { pid_t child_pid = fork(); int status; if(child_pid) { //parent-execution struct rusage child_info; wait4(child_pid, &status, 0, &child_info); if (display_child_time) { printf(CHILD_EXECUTION_TIME_FMT, (float) (child_info.ru_stime.tv_sec + child_info.ru_utime.tv_sec) + (float) (child_info.ru_stime.tv_usec + child_info.ru_utime.tv_usec) / 1000000); } CHILD_OUT_END; handle_exit_status(status); } else { //child execution child_execute_input(envp); } } } else { printf(EOF_ERROR_MSG); exit_shell(); } #if DEBUG dump_buffers(); #endif } LOG_RETURN(0); }
int main(void) { t_all all; int i; f_all(&all); init_shell(&all, environ); while (42) { i = 0; display_prompt(&all); all.env.cmd2exec = scan_for_input(&all); while (all.env.cmd2exec[i]) { if (parse_cmd(&all, all.env.cmd2exec[i])) exec_cmd_input(&all); free_cmd(&all.cmd); i++; } free(all.env.cmd2exec[i]); ft_memdel((void **)&all.env.cmd2exec); } return (0); }
int shell() { int err = 0; extern PCBDLL **PRIORITY_QUEUES; // Makin ur queues PCBDLL_CREATION PRIORITY_QUEUES = PCBDLL_creation( TDF_QUEUES ); buffer_size = BUFFER_SIZE; EXIT_PROMPT_LOOP = 0; strcpy(EXIT_STRING, "exit\0"); welcome_message(); // Debugging check // givemeready(); while (!EXIT_PROMPT_LOOP) { display_prompt(); // `tdf:$ ' currently SYS_REQ_ERR = sys_req(READ, TERMINAL, BUFFER, &buffer_size); err = append_history(BUFFER); PARSER_ERROR = parse_buffer(BUFFER, PARSED_CMD, ARGUMENTS); // The most trivial case if (!strcmp(BUFFER,"\n\0")) { //Just a New Line continue; } switch (PARSER_ERROR) { case PARSER_FAIL_WHITESPACE: continue; break; case PARSER_FAIL_LONGNAME: printf("Invalid command name entered. Must be less than 9 characters.\n"); continue; break; case PARSER_WIN_SINGLETON: //This is linked to PARSER_WIN_HAS_ARGS which follows case PARSER_WIN_HAS_ARGS: if (!strcmp(PARSED_CMD,EXIT_STRING)) { //Equal to EXIT_STRING if(exit_confirmation() == SHELL_EXIT_CONFIRM) { EXIT_PROMPT_LOOP = !EXIT_PROMPT_LOOP; break; } else { continue; } } break; default: printf("I have no idea how you got here. File a bug report!\n"); printf("Parser exited wth status of: %d\n", PARSER_ERROR); continue; break; } if (!strcmp(PARSED_CMD, "date")) { date(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "dispatch")) { dispatch ( ); } else if (!strcmp(PARSED_CMD, "display") || !strcmp(PARSED_CMD, "ls")) { display(ARGUMENTS); continue; } else if (!strcmp(PARSED_CMD, "hossgive")){ givemeready(); } else if (!strcmp(PARSED_CMD, "load")) { load( ARGUMENTS ); } else if (!strcmp(PARSED_CMD, "loadr3")) { loadr3 ( ); } else if (!strcmp(PARSED_CMD, "history")) { history(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "pblock")) { pblock(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "pcreate")) { pcreate(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "pdelete")) { pdelete(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "presume")) { presume(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "psetprio")) { psetprio(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "pshow")) { pshow(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "pshowall")) { pshowall(); } else if (!strcmp(PARSED_CMD, "pshowblk")) { pshowblk(); } else if (!strcmp(PARSED_CMD, "pshowrd")) { pshowrd(); } else if (!strcmp(PARSED_CMD, "psuspend")) { psuspend(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "punblock")) { punblock(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "version")) { version(ARGUMENTS); } else if (!strcmp(PARSED_CMD, "help")) { help(ARGUMENTS); } else { //printf("Command not found.\n"); continue; } } departing_message(); // Clean up our queues PCBDLL_freeall( ); return err; }
int main(int argc, char *argv[]) { DCL_THREADGBL_ACCESS; GTM_THREADGBL_INIT; common_startup_init(DSE_IMAGE); licensed = TRUE; TREF(transform) = TRUE; TREF(no_spangbls) = TRUE; /* dse operates on a per-region basis irrespective of global mapping in gld */ TREF(skip_file_corrupt_check) = TRUE; /* do not let csd->file_corrupt flag cause errors in dse */ op_open_ptr = op_open; patch_curr_blk = get_dir_root(); err_init(util_base_ch); UNICODE_ONLY(gtm_strToTitle_ptr = >m_strToTitle); GTM_ICU_INIT_IF_NEEDED; /* Note: should be invoked after err_init (since it may error out) and before CLI parsing */ sig_init(generic_signal_handler, dse_ctrlc_handler, suspsigs_handler, continue_handler); atexit(util_exit_handler); SET_LATCH_GLOBAL(&defer_latch, LOCK_AVAILABLE); stp_init(STP_INITSIZE); rts_stringpool = stringpool; getjobname(); INVOKE_INIT_SECSHR_ADDRS; io_init(TRUE); getzdir(); gtm_chk_dist(argv[0]); prealloc_gt_timers(); gt_timers_add_safe_hndlrs(); initialize_pattern_table(); gvinit(); region_init(FALSE); util_out_print("!/File !_!AD", TRUE, DB_LEN_STR(gv_cur_region)); util_out_print("Region!_!AD!/", TRUE, REG_LEN_STR(gv_cur_region)); cli_lex_setup(argc, argv); /* Since DSE operates on a region-by-region basis (for the most part), do not use a global directory at all from now on */ original_header = gd_header; gd_header = NULL; OPERATOR_LOG_MSG; # ifdef DEBUG if ((gtm_white_box_test_case_enabled && (WBTEST_SEMTOOLONG_STACK_TRACE == gtm_white_box_test_case_number) )) { sgmnt_addrs * csa; node_local_ptr_t cnl; csa = &FILE_INFO(gv_cur_region)->s_addrs; cnl = csa->nl; cnl->wbox_test_seq_num = 1; /*Signal the first step and wait here*/ /* The signal to the shell. MUPIP must not start BEFORE DSE */ util_out_print("DSE is ready. MUPIP can start. Note: This message is a part of WBTEST_SEMTOOLONG_STACK_TRACE test. " "It will not appear in PRO version.", TRUE); while (2 != cnl->wbox_test_seq_num) /*Wait for another process to get hold of the semaphore and signal next step*/ LONG_SLEEP(1); } # endif if (argc < 2) display_prompt(); while (1) { if (!dse_process(argc)) break; display_prompt(); } dse_exit(); REVERT; return 0; }
void process_uart_data(uint8_t key) { switch(key) { case 'R' : case 'r': { //print_registers(); display_brt_regs(); break; } case 'H': case 'h': { display_help(); break; } case 'D': case 'd': { current_sub_addr = validate_brt_sa_input(); if ( current_sub_addr > 0) { // 0 mean esc from current operation display_brt_data(CORE1553BRT_0 ,current_sub_addr); } break; } case 'M': case 'm': { uint16_t brt_tx_data_addr; current_sub_addr = validate_brt_sa_input(); if ( current_sub_addr > 0) { // 0 mean esc from current brt_tx_data_addr = ( CORE1553BRT_BASE_ADDR + (BRT_RX_SA1 * current_sub_addr) +BRT_RX_TX_ADDR_OFSET) ; //0x1080 modify_mem_data (brt_tx_data_addr,BRT_SUBADDR_DATA_COUNT); } break; } case 'c': case 'C': { uint8_t brt_rtaddr; dp_display_text("Enter New RTADDR # ( 0 to 30): "); brt_rtaddr = get_data_input (); if ((brt_rtaddr > 0 ) && (brt_rtaddr < 31)) { modify_rt_address(CORE1553BRT_BASE_ADDR, brt_rtaddr); break; } else { dp_display_text("\r\n\Invaid input !!!!! Enter Address # ( 0 to 30): "); break; } break; } default: /* If selected key is out of range */ { break; } } display_prompt(); }
/* * Runs commands in parallel mode, with support for background processes. */ char parallel_mode(char **pointers_to_commands, Node *head, Node **paused_list, Node **cpidlist) { int count = 0; // counts the no. of times we've been in the loop; // if more than 1, we need to free // pointers_to_commands, which is different from what we got from main. while (1) { count++; char mode = 'p'; pid_t cpid; char **command; char return_char = 'p'; int i = 0; while (pointers_to_commands[i] != NULL) { command = tokenify(pointers_to_commands[i], " \n\t"); if (command[0] == NULL) { i++; free_tokens(command); continue; } if (handle_exit(command) != 'n') { if (*cpidlist == NULL && pointers_to_commands[i+1] == NULL) { return_char = 'e'; } else { printf("There are processes still running. You cannot exit yet. \n"); } free_tokens(command); i++; continue; } if (is_mode(command)) { return_char = handle_mode(command, mode, return_char); if (return_char == 's') { if (*cpidlist != NULL || pointers_to_commands[i+1] != NULL) { printf("There are processes running. You cannot switch modes yet.\n"); return_char = 'p'; } } free_tokens(command); i++; continue; } if (handle_parallel_builtins(command, paused_list, cpidlist, mode) == 1) { i++; free_tokens(command); continue; } cpid = fork(); if (cpid == 0) { char *tempcommand; tempcommand = prepend_path(command, head); command[0]= tempcommand; if (execv(command[0], command) < 0) { fprintf(stderr, "execv failed: %s\n", strerror(errno)); printf("That's not a valid command! \n"); free_tokens(command); exit(EXIT_FAILURE); } } else { char whole_command[128]; memset(whole_command, '\0', 128); strcat(whole_command, command[0]); if (command[1] != NULL) { strcat(whole_command, " "); strcat(whole_command, command[1]); } char cpidstr[128]; sprintf(cpidstr, "%d", cpid); list_append(cpidstr, whole_command, cpidlist); } i++; free_tokens(command); } if (count > 1) { free_tokens(pointers_to_commands); } if (return_char != 'p') { return return_char; } struct pollfd pfd[1]; pfd[0].fd = 0; pfd[0].events = POLLIN; pfd[0].revents = 0; display_prompt(); int some_process_completed = 0; while (1) { int status; int rv = poll(&pfd[0], 1, 800); Node *to_delete_list = NULL; Node *tempcpidlist = *cpidlist; pid_t w; if (rv == 0) { some_process_completed = 0; while (tempcpidlist != NULL) { w = atoi(tempcpidlist->data); // I know that the ideal way to check for child process death is to use a macro such as WIFEXITED on status, // but it wasn't working for me. // status always had the value 0. So I'm doing this instead to check for process completion. if (waitpid(w, &status, WUNTRACED|WNOHANG) == -1) { list_append(tempcpidlist->data, "", &to_delete_list); printf("\nProcess %s (%s) completed.\n", tempcpidlist->data, tempcpidlist->additional_data); some_process_completed = 1; } tempcpidlist = tempcpidlist->next; } Node *curr = to_delete_list; while (curr != NULL) { list_delete(curr->data, cpidlist); curr = curr->next; } list_clear(to_delete_list); if (some_process_completed == 1) { display_prompt(); } } else if (rv > 0) { char buffer[1024]; if (fgets(buffer, 1024, stdin) == NULL) { if (*cpidlist != NULL) { printf("There are processes still running. You can't exit now.\n"); display_prompt(); } else { return_char = 'e'; return return_char; } } else { char *newbuffer = replace_pound(buffer); newbuffer[strlen(newbuffer)-1] = '\0'; pointers_to_commands = tokenify(newbuffer, ";"); free(newbuffer); break; } } else { printf("there was some kind of error: %s \n", strerror(errno)); } } } }
/* Functions */ int main(int argc, char *argv[] ) { FILE *rules, *map; /* Pointers to rules/map file streams */ Grid board; /* Store info about the game board */ Ship ships[MAX_SHIPS]; /* Store info about each ship */ int **answer; /* Store the solution of the game */ unsigned int numShips = 0; /* Store the total numberof ships */ unsigned int xGuess, yGuess;/* Store the player's current guess */ /* Temp Variables */ int status = 0; /* exit status */ int i = 0, j = 0; /* loop indeces */ /* There must be at least three parameters */ if(argc < 3) { return params_missing(); } /* Save rules file into "rules", it's OK if "standard.rules" DNE * Rules file must be readable unless it is standard.rules */ if((rules = fopen(argv[1], "r")) == NULL) { if(!strcmp(argv[1], "standard.rules")) { fclose(rules); /* Looking for "standard.rules" but file DNE so create it * with the default contents */ rules = fopen(argv[1], "w"); fprintf(rules, "8 8\n5\n5\n4\n3\n2\n1\n\n"); fclose(rules); rules = fopen(argv[1], "r"); } else { return rules_missing(); } fclose(rules); } /* Save map file into "map" * Map file must be readable */ if((map = fopen(argv[2], "r")) == NULL ) { fclose(map); return maps_missing(); } /* Save and check rules file * Rules must conform to specification */ if((status = parse_rules(rules, ships, &board, &numShips))) { return status; } /* Initialize the answer array */ answer = (int**)malloc(board.width * sizeof(int*)); for(i = 0; i < board.width; i++) { answer[i] = (int*)malloc(board.height * sizeof(int)); for(j = 0; j < board.height; j++) { answer[i][j] = 1; } } /* Save and check map file * Map must conform to specification */ if((status = parse_map(map, ships, &board, &numShips))) { return status; } /* Populate the solution */ if((status = place_ships(ships, numShips, answer))) { return status; } /* Interaction Loop */ for(;;) { display_board(board.width, board.height, answer); display_prompt(); switch(get_prompt(&xGuess, &yGuess)) { case 0: make_guess(&xGuess, &yGuess, &board, answer); break; case 1: printf("Bad guess\n"); break; case -1: return bad_guess(); } } return 0; }