int validate_mfg_card(char *device, int fd) { int ret = 0; struct ata_ioc_request *req; req = build_basic_command(0, 1, 0, ATA_ATA_IDENTIFY, ATA_CMD_READ, SECTOR_SIZE); ret = execute_command(req, fd); if(ret) err(1, "Validate mfg execute command failed.%d %d ",ret, errno); ret = validate_card(req->data); if (ret == 0) { show_details_disk(req->data, device); } else { noupdate_details_disk(device); } free_request(req); return ret; }
void BE_update_callgraph() { printf("\nUpdate Call Graph!\n"); execute_command("interrupt",0); wait_for_inferior(); normal_stop(); struct ME_CG * stack; BE_get_call_stack_as_CG(NULL, 0, 0, 1, &stack, the_context.FT); continue_command_JG(); if (!the_context.CG) { the_context.CG = stack; } else { ME_CG_merge_stack(the_context.CG,stack); ME_CG_delete(stack); } ME_CG_print(the_context.CG,the_context.FT); //execute_command("detach",1); }
static int init_rcfile(void) { int ret = 0; char buf[BUFSIZ]; struct stat st; FILE *f; if (rcfile == NULL) { rcfile = ne_concat(getenv("HOME"), "/.cadaverrc", NULL); if (stat(rcfile, &st) != 0) { NE_DEBUG(DEBUG_FILES, "No rcfile\n"); free(rcfile); return 0; } } f = fopen(rcfile, "r"); if (f == NULL) { printf(_("Could not read rcfile %s: %s\n"), rcfile, strerror(errno)); } else { for (;;) { if (fgets(buf, BUFSIZ, f) != NULL) { ret = execute_command(ne_shave(buf, "\r\n")); if (ret != 0) break; } else { break; } } fclose(f); } free(rcfile); return ret; }
static void exec_reverse_once (char *cmd, char *args, int from_tty) { char *reverse_command; enum exec_direction_kind dir = execution_direction; struct cleanup *old_chain; if (dir == EXEC_ERROR) error (_("Target %s does not support this command."), target_shortname); if (dir == EXEC_REVERSE) error (_("Already in reverse mode. Use '%s' or 'set exec-dir forward'."), cmd); if (!target_can_execute_reverse) error (_("Target %s does not support this command."), target_shortname); reverse_command = xstrprintf ("%s %s", cmd, args ? args : ""); old_chain = make_cleanup (exec_direction_default, NULL); make_cleanup (xfree, reverse_command); execution_direction = EXEC_REVERSE; execute_command (reverse_command, from_tty); do_cleanups (old_chain); }
// Polling function to be called from the main event loop. void poll_command_input(void) { while (Serial.available()) { int next_char = Serial.read(); // once a line terminator is received, process the available command string if (next_char == '\r') { command_buffer[next_command_char] = 0; // terminate the string // parse the string into pieces and execute them char *argv[max_command_terms]; int argc = parse_arg_line( command_buffer, argv, max_command_terms); execute_command(argc, argv); // then reset the command buffer next_command_char = 0; } // else store the characters until a full line is received, ignoring overrun if (next_command_char < max_command_length) { command_buffer[next_command_char++] = next_char; } } }
void ldplayer_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) { switch (id) { case TIMER_ID_VSYNC_UPDATE: { // handle commands if (param == 0) process_commands(); // set a timer to go off on the next VBLANK int vblank_scanline = machine().primary_screen->visible_area().max_y + 1; attotime target = machine().primary_screen->time_until_pos(vblank_scanline); timer_set(target, TIMER_ID_VSYNC_UPDATE); break; } case TIMER_ID_AUTOPLAY: // start playing execute_command(CMD_PLAY); m_playing = true; break; } }
int ret_history(t_datas *data, t_history *history, char *str) { int nb; int i; t_history *tmp; str += 1; i = 0; tmp = history; if (str != 0) { nb = my_getnbr(str); while (tmp != NULL && i != nb) { tmp = tmp->next; i += 1; } if (i != nb || tmp == NULL) return (my_int_perror("Event not found\n", 0)); if ((execute_command(data, tmp->command)) == -1) return (my_int_perror("Failed to exec function\n", -1)); } return (0); }
/* Read more data from scsi device into buffer. */ static void scsi_read_data(SCSIRequest *req) { SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req); SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, r->req.dev); int ret; DPRINTF("scsi_read_data 0x%x\n", req->tag); if (r->len == -1) { scsi_command_complete(r, 0); return; } if (r->req.cmd.buf[0] == REQUEST_SENSE && s->driver_status & SG_ERR_DRIVER_SENSE) { s->senselen = MIN(r->len, s->senselen); memcpy(r->buf, s->sensebuf, s->senselen); r->io_header.driver_status = 0; r->io_header.status = 0; r->io_header.dxfer_len = s->senselen; r->len = -1; DPRINTF("Data ready tag=0x%x len=%d\n", r->req.tag, s->senselen); DPRINTF("Sense: %d %d %d %d %d %d %d %d\n", r->buf[0], r->buf[1], r->buf[2], r->buf[3], r->buf[4], r->buf[5], r->buf[6], r->buf[7]); scsi_req_data(&r->req, s->senselen); /* Clear sensebuf after REQUEST_SENSE */ scsi_clear_sense(s); return; } ret = execute_command(s->bs, r, SG_DXFER_FROM_DEV, scsi_read_complete); if (ret < 0) { scsi_command_complete(r, ret); return; } }
int run_command(const char *cmd) { char cmdbuf[CONFIG_CBSIZE]; /* working copy of cmd */ char *token; /* start of token in cmdbuf */ char *sep; /* end of token (separator) in cmdbuf */ char finaltoken[CONFIG_CBSIZE]; char *str = cmdbuf; char *argv[CONFIG_MAXARGS + 1]; /* NULL terminated */ int argc, inquotes; int rc = 0; #ifdef DEBUG pr_debug("[RUN_COMMAND] cmd[%p]=\"", cmd); puts (cmd ? cmd : "NULL"); /* use puts - string may be loooong */ puts ("\"\n"); #endif if (!cmd || !*cmd) { return -1; /* empty command */ } if (strlen(cmd) >= CONFIG_CBSIZE) { puts ("## Command too long!\n"); return -1; } strcpy (cmdbuf, cmd); /* * Process separators and check for invalid * repeatable commands */ pr_debug("[PROCESS_SEPARATORS] %s\n", cmd); while (*str) { /* * Find separator, or string end * Allow simple escape of ';' by writing "\;" */ for (inquotes = 0, sep = str; *sep; sep++) { if ((*sep=='\'') && (*(sep-1) != '\\')) inquotes=!inquotes; if (!inquotes && (*sep == ';') && /* separator */ ( sep != str) && /* past string start */ (*(sep-1) != '\\')) /* and NOT escaped */ break; } /* * Limit the token to data between separators */ token = str; if (*sep) { str = sep + 1; /* start of command for next pass */ *sep = '\0'; } else { str = sep; /* no more commands for next pass */ } pr_debug("token: \"%s\"\n", token); /* find macros in this token and replace them */ process_macros (token, finaltoken); /* Extract arguments */ if ((argc = parse_line (finaltoken, argv)) == 0) { rc = -1; /* no command at all */ continue; } if (execute_command(argc, argv) != COMMAND_SUCCESS) rc = -1; } return rc; }
void ldplayer_state::process_commands() { input_port_value controls = input_port_read(machine(), "controls"); int number; // step backwards if (!(m_last_controls & 0x01) && (controls & 0x01)) execute_command(CMD_STEP_REVERSE); // step forwards if (!(m_last_controls & 0x02) && (controls & 0x02)) execute_command(CMD_STEP_FORWARD); // scan backwards if (controls & 0x04) execute_command(CMD_SCAN_REVERSE); // scan forwards if (controls & 0x08) execute_command(CMD_SCAN_FORWARD); // slow backwards if (!(m_last_controls & 0x10) && (controls & 0x10)) execute_command(CMD_SLOW_REVERSE); // slow forwards if (!(m_last_controls & 0x20) && (controls & 0x20)) execute_command(CMD_SLOW_FORWARD); // fast backwards if (controls & 0x40) execute_command(CMD_FAST_REVERSE); // fast forwards if (controls & 0x80) execute_command(CMD_FAST_FORWARD); // play/pause if (!(m_last_controls & 0x100) && (controls & 0x100)) { m_playing = !m_playing; execute_command(m_playing ? CMD_PLAY : CMD_PAUSE); } // toggle frame display if (!(m_last_controls & 0x200) && (controls & 0x200)) execute_command(CMD_FRAME_TOGGLE); // toggle chapter display if (!(m_last_controls & 0x400) && (controls & 0x400)) execute_command(CMD_CHAPTER_TOGGLE); // toggle left channel if (!(m_last_controls & 0x800) && (controls & 0x800)) execute_command(CMD_CH1_TOGGLE); // toggle right channel if (!(m_last_controls & 0x1000) && (controls & 0x1000)) execute_command(CMD_CH2_TOGGLE); // numbers for (number = 0; number < 10; number++) if (!(m_last_controls & (0x10000 << number)) && (controls & (0x10000 << number))) execute_command(CMD_0 + number); // enter if (!(m_last_controls & 0x4000000) && (controls & 0x4000000)) execute_command(CMD_SEARCH); m_last_controls = controls; }
int main(int argc, char **argv) { int status; struct sigaction usr_action; struct sigaction term_action; sigset_t block_mask; int socks_status; connections.last_slot = -1; connections.running_pid = getpid(); status = init(argc, argv, &connections); if (status == INIT_FAILURE) { if (to_printhelp == 1) print_help(argc, argv); exit(EXIT_FAILURE); } if (status == INIT_SUCCESS && to_printhelp == 1) { print_help(argc, argv); exit(EXIT_SUCCESS); } if (to_command_mode) { status = execute_command(&connections); exit(status); } Log(LOG_NOTICE, "Program started by User %d \n", getuid()); /* Daemon-specific initialization */ if (to_demonize) { status = daemonize(&connections); switch (status) { case DAEMONIZE_FAILURE: /*something gone wrong exit from parent */ printf("Failed to daemonize.Check permissions\n"); exit(EXIT_FAILURE); break; case DAEMONIZE_SUCCESS: /*ok we are the parent, we can exit gracefully */ Log(LOG_INFO, "Starting as a daemon.Parent exit\n"); printf("Starting as a daemon.Parent exit\n"); exit(EXIT_SUCCESS); break; } } /* Establish the signal handler. */ sigfillset(&block_mask); usr_action.sa_handler = sleep_signal; usr_action.sa_mask = block_mask; usr_action.sa_flags = 0; sigaction(SIGUSR1, &usr_action, NULL); term_action.sa_handler = term_signal; term_action.sa_mask = block_mask; term_action.sa_flags = 0; sigaction(SIGTERM, &term_action, NULL); Log(LOG_INFO, "Init networking\n"); status = initialize_network(&connections); Log(LOG_INFO, "Init timers\n"); status = initialize_timers(&connections); /* The Big Loop */ while (1) { Log(LOG_DEBUG, "Main loop\n"); rebuild_connection_set(&connections); socks_status = select(connections.max_socket + 1, &connections.socket_set, NULL, NULL, NULL); if (socks_status < 0) { status = errno; /* We had an error, signal it */ if (status != EINTR) { Log(LOG_ERR, "Error in select socket (%s) \n", strerror(status)); exit(EXIT_FAILURE); } } else if (socks_status == 0) { /* Nothing to do probably a staying alive msg in debug mode */ } else { read_sockets(&connections); } } closelog(); exit(EXIT_SUCCESS); }
void execute_pipe_command (command_t c) { int pipefd[2]; if (pipe(pipefd) == -1) { error(1, 0, "Can't create a pipe"); return; } pid_t pid1 = fork(); if (pid1 <0 ) //error { error (1, 0, "Can't fork."); return; } else if (pid1 == 0) //we are in child process { close(pipefd[0]); //close read end (fd[0]) close (1); //关闭输入流 if (dup2(pipefd[1],1) == -1) //write: int dup2(int oldfd, int newfd) error(1,0, "Can't write to pipe."); execute_command(c->u.command[0], time_travel); //c->status = c->u.command[0]->status; close (pipefd[1]); exit (c->u.command[0]->status); } // we are in parent process else { close (pipefd[1]); //close write end close (0); //关闭输出流 if (dup2(pipefd[0],0) < 0) error(1,0,"Can't read from pipe."); execute_command (c->u.command[1], time_travel); //c->status = c->u.command[1]-status; close (pipefd[0]); exit(c->u.command[0]->status); waitpid(pid1, &(c->status), 0); close (pipefd[0]); /* pid_t pid2 = fork(); if (pid2<0) { error (1, 0, "Can't fork."); } else if (pid2 == 0) //another child { close (pipefd[1]); //close write end close (0); //关闭输出流 if (dup2(pipefd[0],0) < 0) error(1,0,"Can't read from pipe."); execute_command (c->u.command[1], time_travel); //c->status = c->u.command[1]-status; close (pipefd[0]); exit(c->u.command[0]->status); } else //parent { close(pipefd[0]); close(pipefd[1]); pid_t wait_pid = waitpid(-1, &(c->status), 0); //which child exits last determines the status if (wait_pid == pid1) { waitpid(pid2, &(c->status), 0); return; } if (wait_pid == pid2) { waitpid(pid1, &(c->status), 0); return; } }*/ } }
void execute_time_travel_stream(command_stream_t command_stream) { //in the time travel mode, the command_stream is the one passed to the arguments command_stream_t track = command_stream_head; //pid_t* children = checked_malloc(runnable * sizeof(pid_t)); //int i = 0; if(track ==NULL) { error(1,0, "Error: the command stream is empty."); //printf("The command stream is empty\n"); return; } build_waitlist(command_stream, outfile_head); while(track != NULL) { //int check = check_dependency(track->p_command,outfile_head); //printf("%d\n",check); if(track->p_command->dependency== 0) { pid_t pid = fork(); if(pid == 0) { printf("children0\n"); execute_command(track->p_command, 0); printf("children1\n"); wakeup_waitlist(track->p_command); printf("children2\n"); if (track->p_command-> outfile_ptr != NULL) delete_outfile(track->p_command-> outfile_ptr); printf("children3\n"); exit(track->p_command->status); } else if (pid > 0) { //;//children[i] = child; { //int status; // wait for the child process //if ( (waitpid(pid, NULL, 0)) == -1) //printf ("parent"); pidArray[countArray] = pid; countArray++; //error(1, errno, "Child process error"); // harvest the execution status //printf("parent: %d\n", status); //c->status = WEXITSTATUS(status); //0 indicates that the command is exited } } else error(3, 0, "Cannot create child process."); //i++; track = track ->next; } else { printf("Has depends\n"); track = track->next; } } int countloop = 0; while (countloop < countArray ) { if (pidArray[countloop] > 0) waitpid(pidArray[countloop], NULL, 0); countloop++; } // execute ready list }
void execute_time_travel(command_stream_t command_stream) { command_t command; // Initialize array for all commands List command_list = create_list(); // For each command in the command stream while ((command = read_command_stream(command_stream))) { // Initialize a new node for the command Node* new_node = create_node(command); // Determine all of its dependencies and add it to the node // For dependencies need to determine input files and output files determine_dependencies(command, new_node); // Push the new command node on to the array list_insert(&command_list, new_node); } // While there are still commands in the array while (command_list.counter > 0) { Node* iter = command_list.begin; int i; // For each command in the array for (i = 0; i < command_list.counter; i++) { // Check to make sure none of it's input files is equal to any of // the output files of the previous commands // If it doesn't depend on any of the previous commands then we // should create a fork and execute the process if (no_dependencies(iter, i) && !iter->executed) { iter->executed = true; pid_t pid = fork(); // If we are in the child process if (pid == 0) { // Execute the command execute_command(iter->c); // Exit the process _exit(0); } // If we are the parent set that positions pid to the pid of the // process just created else if (pid > 0) { iter->pid = pid; }else error(1, 0, "Forked process Failed"); } iter = iter->next_node; } // Wait for any process to finish pid_t finished_pid = waitpid(-1, NULL, 0); // Find that process in the array and remove it from the array list_remove(&command_list, finished_pid); } }
void execute_command (command_t c, int time_travel) { /* FIXME: Replace this with your implementation. You may need to add auxiliary functions and otherwise modify the source code. You can also use external functions defined in the GNU C Library. */ //+error (1, 0, "command execution not yet implemented"); //Implementation //Get rid of error dummy code // c->status; // time_travel; //End-Implementation pid_t childpid; if(c->type == SIMPLE_COMMAND) { if(!(childpid = fork())){ if(c->input != NULL){ int fd = open(c->input, O_RDWR); if(fd == -1){ goto exe_inout_error; } if(dup2(fd, 0)==-1){ // 0 = std_in goto exe_dup_error; } close(fd); } if(c->output != NULL){ int fd = open(c->output, O_RDWR|O_CREAT|O_TRUNC, 0666); if(fd == -1){ goto exe_inout_error; } if(dup2(fd, 1)==-1){// 1 = std_out goto exe_dup_error; } close(fd); } execvp(c->u.word[0], c->u.word); goto exe_error; } else{ int status=0; waitpid(childpid, &status,0); c->status = WEXITSTATUS(status); } } else if(c->type == SUBSHELL_COMMAND){ execute_command(c->u.subshell_command, time_travel); c->status = WEXITSTATUS(c->u.subshell_command->status); } else if(c->type == SEQUENCE_COMMAND) { if (!(childpid=fork())) { execute_command(c->u.command[0], time_travel); exit(c->u.command[0]->status); } else{ int status =0; int retpid = waitpid(childpid, &status, 0); c->status = WEXITSTATUS(status); execute_command(c->u.command[1], time_travel); c->status = WEXITSTATUS(c->u.command[1]->status); } } else if(c->type == PIPE_COMMAND){ int pipefd[2]; pipe(pipefd); pid_t left, right; if(!(left=fork())) { if(dup2(pipefd[1],1)==-1){ goto exe_dup_error; } close(pipefd[0]); execute_command(c->u.command[0], time_travel); //c->status = c->u.command[0]->status; close(pipefd[1]); exit(c->u.command[0]->status); // for parent waitpid } else { int status=0; waitpid(left, &status,0); if (!(right = fork())) { if(dup2(pipefd[0],0)==-1){ goto exe_dup_error; } close(pipefd[1]); execute_command(c->u.command[1], time_travel); //if(status == ERROR){ report error}; else ... //c->u.command[1]->status; close(pipefd[0]); exit(c->u.command[1]->status); } else { close(pipefd[1]); close(pipefd[0]); pid_t retpid = waitpid(-1, &status,0); if(left == retpid) { waitpid(right,&status,0); c->status = WEXITSTATUS(status); } else{ c->status = WEXITSTATUS(status); waitpid(left,&status,0); } } } } else if(c->type == AND_COMMAND || c->type == OR_COMMAND) { if (!(childpid=fork())) { execute_command(c->u.command[0], time_travel); exit(c->u.command[0]->status); } else { int status; waitpid(childpid,&status,0); status = WEXITSTATUS(status); if (((status == 0) && (c->type == AND_COMMAND))|| ((status != 0) && (c->type == OR_COMMAND))) { execute_command(c->u.command[1], time_travel); c->status = c->u.command[1]->status; } } } else{ error(7, 0, "Execution Error, invalid type of command"); } if(0) { exe_error:; error(7, 0, "Execution Error, single command failure"); return; exe_dup_error:; error(7, 0, "Execution Error, dup2() error"); return; exe_inout_error:; error(7, 0, "Execution Error, inout file open error"); return; } return; }
inline void delete_(Connection & conn, PrimaryKey const& key) { execute_command(conn, sql::create_delete_sql<Connection, Entity>(key)); detail::post_delete_check(conn); }
static void *client_thread(void *arg) { ssize_t nwritten; pthread_detach(pthread_self()); int client_fd = (int) (long) arg; int yes = 1, tcp_keepalive_probes = 3, tcp_keepalive_time = 5, tcp_keepalive_intvl = 2; int nodelay = 1; if (setsockopt(client_fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) == -1) { log_error("setsockopt failed: %s", strerror(errno)); close(client_fd); return NULL; } if (setsockopt(client_fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepalive_probes, sizeof(tcp_keepalive_probes)) == -1) { log_error("setsockopt failed: %s", strerror(errno)); close(client_fd); return NULL; } if (setsockopt(client_fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepalive_time, sizeof(tcp_keepalive_time)) == -1) { log_error("setsockopt failed: %s", strerror(errno)); close(client_fd); return NULL; } if (setsockopt(client_fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepalive_intvl, sizeof(tcp_keepalive_intvl)) == -1) { log_error("setsockopt failed: %s", strerror(errno)); close(client_fd); return NULL; } if (setsockopt(client_fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) == -1) { log_error("setsockopt failed: %s", strerror(errno)); close(client_fd); return NULL; } size_t request_size = 8192; struct request *request_back = NULL; struct request *request = (struct request *) malloc(request_size); if (!request) { log_error("malloc failed: %s", strerror(errno)); close(client_fd); return NULL; } msgpack_unpacked msg; msgpack_unpacked_init(&msg); bool enable_gzip = false; while (1) { struct response_header response_header; ssize_t recvsize = readn(client_fd, request, sizeof(struct request)); if (!recvsize) { log_warn("peer closed connection"); break; } if (recvsize < (ssize_t) sizeof(struct request)) { log_warn("error while receiving header, received %zd", recvsize); break; } if (request->payload_size > 256 * 1024 * 1024) { log_warn("payload size %"PRIu32" too large", request->payload_size); break; } if (sizeof(struct request) + request->payload_size > request_size) { request_size = sizeof(struct request) + request->payload_size; request_back = request; request = realloc(request, request_size); if (!request) { log_error("realloc failed: %s", strerror(errno)); free(request_back); break; } } recvsize = readn(client_fd, request->payload, request->payload_size); if (!recvsize) { log_warn("peer closed connection"); break; } if (recvsize < request->payload_size) { log_warn("error while receiving payload, received %zd (should be %"PRIu32")", recvsize, request->payload_size); break; } if (request->flags & REQUEST_FLAG_GZIP) { enable_gzip = true; uLongf destLen = 16; Bytef *dest = malloc(destLen); if (!dest) { log_error("malloc failed: %s", strerror(errno)); break; } int ret; keep_malloc: ret = uncompress(dest, &destLen, (Bytef *) request->payload, request->payload_size); if (ret == Z_BUF_ERROR) { destLen = destLen * 2; free(dest); dest = malloc(destLen); if (!dest) { log_error("malloc failed: %s", strerror(errno)); break; } goto keep_malloc; } if (ret != Z_OK) { free(dest); break; } request->flags &= ~REQUEST_FLAG_GZIP; if (sizeof(struct request) + destLen > request_size) { request_size = sizeof(struct request) + destLen; request_back = request; request = realloc(request, request_size); if (!request) { log_error("realloc failed: %s", strerror(errno)); free(request_back); free(dest); break; } } memcpy(request->payload, dest, destLen); request->payload_size = destLen; free(dest); } bool success = msgpack_unpack_next(&msg, request->payload, request->payload_size, NULL); if (!success) { log_warn("error while parsing payload"); break; } msgpack_sbuffer* buffer = msgpack_sbuffer_new(); msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write); response_header.seq = request->seq; __sync_add_and_fetch(&pending_commands, 1); if (server->terminated) { __sync_add_and_fetch(&pending_commands, -1); break; } if (server->redirection) { response_header.status = RESPONSE_STATUS_REDIRECTION; msgpack_pack_map(pk, 2); mp_pack_string(pk, "host"); mp_pack_string(pk, server->redirection->host); mp_pack_string(pk, "port"); msgpack_pack_uint16(pk, server->redirection->port); } else { response_header.status = execute_command(request, request->command, msg.data, pk); } __sync_add_and_fetch(&pending_commands, -1); msgpack_packer_free(pk); if (!(request->flags & REQUEST_FLAG_NO_REPLY)) { if (!(buffer->size > 0)) { response_header.payload_size = 0; nwritten = writen(client_fd, &response_header, sizeof(response_header)); if (!nwritten) { log_error("writen failed: %s", strerror(errno)); msgpack_sbuffer_free(buffer); break; } } else { if (!enable_gzip) { response_header.payload_size = buffer->size; nwritten = writen(client_fd, &response_header, sizeof(response_header)); if (!nwritten) { log_error("writen failed: %s", strerror(errno)); msgpack_sbuffer_free(buffer); break; } nwritten = writen(client_fd, buffer->data, buffer->size); if (!nwritten) { log_error("writen failed: %s", strerror(errno)); msgpack_sbuffer_free(buffer); break; } } else { uLongf destLen = buffer->size * 1.00101 + 13; Bytef *dest = malloc(destLen); if (!dest) { log_error("malloc failed: %s", strerror(errno)); msgpack_sbuffer_free(buffer); break; } int ret = compress(dest, &destLen, (Bytef *) buffer->data, buffer->size); while (ret == Z_BUF_ERROR) { destLen = destLen * 2 + 16; free(dest); dest = malloc(destLen); if (!dest) { log_error("malloc failed: %s", strerror(errno)); msgpack_sbuffer_free(buffer); break; } ret = compress(dest, &destLen, (Bytef *) buffer->data, buffer->size); } if (ret != Z_OK) { log_error("error while compressing response: %d", ret); if (dest) free(dest); break; } response_header.payload_size = destLen; nwritten = writen(client_fd, &response_header, sizeof(response_header)); if (!nwritten) { log_warn("peer closed connection"); msgpack_sbuffer_free(buffer); free(dest); break; } if (nwritten < 0) { log_error("send response header failed: %s", strerror(errno)); msgpack_sbuffer_free(buffer); free(dest); break; } if (nwritten < (ssize_t)sizeof(response_header)) { log_warn("error while sending response header, sent %zd (should be %"PRIu64")", nwritten, sizeof(response_header)); msgpack_sbuffer_free(buffer); free(dest); break; } nwritten = writen(client_fd, dest, destLen); if (!nwritten) { log_warn("peer closed connection"); msgpack_sbuffer_free(buffer); free(dest); break; } if (nwritten < 0) { log_error("send response failed: %s", strerror(errno)); msgpack_sbuffer_free(buffer); free(dest); break; } if (nwritten < (ssize_t)destLen) { log_warn("error while sending response, sent %zd (should be %"PRIu64")", nwritten, destLen); msgpack_sbuffer_free(buffer); free(dest); break; } free(dest); } } } msgpack_sbuffer_free(buffer); if (request_size > 65536) { request_size = 8192; request_back = request; request = realloc(request, request_size); if (!request) { log_error("realloc failed: %s", strerror(errno)); free(request_back); break; } } } close(client_fd); free(request); msgpack_unpacked_destroy(&msg); return NULL; }
static int sb600_spi_send_command(struct flashctx *flash, unsigned int writecnt, unsigned int readcnt, const unsigned char *writearr, unsigned char *readarr) { int count; /* First byte is cmd which can not being sent through FIFO. */ unsigned char cmd = *writearr++; unsigned int readoffby1; unsigned char readwrite; writecnt--; msg_pspew("%s, cmd=%x, writecnt=%x, readcnt=%x\n", __func__, cmd, writecnt, readcnt); if (readcnt > 8) { msg_pinfo("%s, SB600 SPI controller can not receive %d bytes, " "it is limited to 8 bytes\n", __func__, readcnt); return SPI_INVALID_LENGTH; } if (writecnt > 8) { msg_pinfo("%s, SB600 SPI controller can not send %d bytes, " "it is limited to 8 bytes\n", __func__, writecnt); return SPI_INVALID_LENGTH; } /* This is a workaround for a bug in SB600 and SB700. If we only send * an opcode and no additional data/address, the SPI controller will * read one byte too few from the chip. Basically, the last byte of * the chip response is discarded and will not end up in the FIFO. * It is unclear if the CS# line is set high too early as well. */ readoffby1 = (writecnt) ? 0 : 1; readwrite = (readcnt + readoffby1) << 4 | (writecnt); mmio_writeb(readwrite, sb600_spibar + 1); mmio_writeb(cmd, sb600_spibar + 0); /* Before we use the FIFO, reset it first. */ reset_internal_fifo_pointer(); /* Send the write byte to FIFO. */ msg_pspew("Writing: "); for (count = 0; count < writecnt; count++, writearr++) { msg_pspew("[%02x]", *writearr); mmio_writeb(*writearr, sb600_spibar + 0xC); } msg_pspew("\n"); /* * We should send the data by sequence, which means we need to reset * the FIFO pointer to the first byte we want to send. */ if (reset_compare_internal_fifo_pointer(writecnt)) return SPI_PROGRAMMER_ERROR; msg_pspew("Executing: \n"); execute_command(); /* * After the command executed, we should find out the index of the * received byte. Here we just reset the FIFO pointer and skip the * writecnt. * It would be possible to increase the FIFO pointer by one instead * of reading and discarding one byte from the FIFO. * The FIFO is implemented on top of an 8 byte ring buffer and the * buffer is never cleared. For every byte that is shifted out after * the opcode, the FIFO already stores the response from the chip. * Usually, the chip will respond with 0x00 or 0xff. */ if (reset_compare_internal_fifo_pointer(writecnt + readcnt)) return SPI_PROGRAMMER_ERROR; /* Skip the bytes we sent. */ msg_pspew("Skipping: "); for (count = 0; count < writecnt; count++) { cmd = mmio_readb(sb600_spibar + 0xC); msg_pspew("[%02x]", cmd); } msg_pspew("\n"); if (compare_internal_fifo_pointer(writecnt)) return SPI_PROGRAMMER_ERROR; msg_pspew("Reading: "); for (count = 0; count < readcnt; count++, readarr++) { *readarr = mmio_readb(sb600_spibar + 0xC); msg_pspew("[%02x]", *readarr); } msg_pspew("\n"); if (reset_compare_internal_fifo_pointer(readcnt + writecnt)) return SPI_PROGRAMMER_ERROR; if (mmio_readb(sb600_spibar + 1) != readwrite) { msg_perr("Unexpected change in SB600 read/write count!\n"); msg_perr("Something else is accessing the flash chip and " "causes random corruption.\nPlease stop all " "applications and drivers and IPMI which access the " "flash chip.\n"); return SPI_PROGRAMMER_ERROR; } return 0; }
int main( int argc, char **argv ) { static const char *progname = PACKAGE; int retval = SUCCESS; int status; dfu_device_t dfu_device; struct programmer_arguments args; #ifdef HAVE_LIBUSB_1_0 struct libusb_device *device = NULL; #else struct usb_device *device = NULL; #endif memset( &args, 0, sizeof(args) ); memset( &dfu_device, 0, sizeof(dfu_device) ); status = parse_arguments(&args, argc, argv); if( status < 0 ) { /* Exit with an error. */ return ARGUMENT_ERROR; } else if (status > 0) { /* It was handled by parse_arguments. */ return SUCCESS; } #ifdef HAVE_LIBUSB_1_0 if (libusb_init(&usbcontext)) { fprintf( stderr, "%s: can't init libusb.\n", progname ); return DEVICE_ACCESS_ERROR; } #else usb_init(); #endif if( debug >= 200 ) { #ifdef HAVE_LIBUSB_1_0 libusb_set_debug(usbcontext, debug ); #else usb_set_debug( debug ); #endif } if( !(args.command == com_bin2hex || args.command == com_hex2bin) ) { device = dfu_device_init( args.vendor_id, args.chip_id, args.bus_id, args.device_address, &dfu_device, args.initial_abort, args.honor_interfaceclass ); if( NULL == device ) { fprintf( stderr, "%s: no device present.\n", progname ); retval = DEVICE_ACCESS_ERROR; goto error; } } if( 0 != (retval = execute_command(&dfu_device, &args)) ) { /* command issued a specific diagnostic already */ goto error; } error: if( NULL != dfu_device.handle ) { int rv; #ifdef HAVE_LIBUSB_1_0 rv = libusb_release_interface( dfu_device.handle, dfu_device.interface ); #else rv = usb_release_interface( dfu_device.handle, dfu_device.interface ); #endif /* The RESET command sometimes causes the usb_release_interface command to fail. It is not obvious why this happens but it may be a glitch due to the hardware reset in the attached device. In any event, since reset causes a USB detach this should not matter, so there is no point in raising an alarm. */ if( 0 != rv && !(com_launch == args.command && args.com_launch_config.noreset == 0) ) { fprintf( stderr, "%s: failed to release interface %d.\n", progname, dfu_device.interface ); retval = DEVICE_ACCESS_ERROR; } } if( NULL != dfu_device.handle ) { #ifdef HAVE_LIBUSB_1_0 libusb_close(dfu_device.handle); #else if( 0 != usb_close(dfu_device.handle) ) { fprintf( stderr, "%s: failed to close the handle.\n", progname ); retval = DEVICE_ACCESS_ERROR; } #endif } #ifdef HAVE_LIBUSB_1_0 libusb_exit(usbcontext); #endif return retval; }
int main (int argc, char **argv) { int command_number = 1; bool print_tree = false; bool time_travel = false; bool output_to_file=false; bool error_to_file=false; bool all_to_file=false; program_name = argv[0]; for (;;) switch (getopt (argc, argv, "ptvxoehas")) { case 'p': print_tree = true; break; case 't': time_travel = true; break; case 'x': x_option=true;break; case 'v': v_option=true;break; case 'o': output_to_file=true;break; case 'e': error_to_file=true;break; case 'a': all_to_file=true;break; case 's': s_option=true;break; case 'h': fprintf(stderr,"option p to print command trees without execution.\noption t to exploit parallelism between command trees.\n"); fprintf(stderr,"option x to print simple commands and their arguments before execution.\noption v to print shell input before execution.\n"); fprintf(stderr,"option o to save output to output.txt.\noption e to save error to error.txt.\n"); fprintf(stderr,"option a to save output and error to output_and_error.txt.\n"); fprintf(stderr,"option s to slowly go through script, one command tree at a time\n"); fprintf(stderr,"option x and v not available in combination with option t.\n"); fprintf(stderr,"options x or v in combination with option s to tell what the next command is before continuing.\n"); return 0; default: usage (); break; case -1: goto options_exhausted; } options_exhausted:; // There must be exactly one file argument. if (optind != argc - 1) usage (); if(time_travel) { if(x_option || v_option || s_option) { no_debug_time_travel(); } } if(print_tree && s_option) { error (1, 0, "usage: %s [-pxvtoehas] SCRIPT-FILE, cannot use step_mode and print tree", program_name); } script_name = argv[optind]; if(s_option) { fprintf(stderr,"Step mode enabled. Press d to disable step mode, press a to abort further execution, or press enter to move onto the next command.\n"); } if (all_to_file==false) { if(output_to_file==true) { int fd=open("output.txt",O_CREAT|O_TRUNC|O_WRONLY,0644); if(fd<0) { fprintf(stderr,"No available file descriptors"); return(1); } dup2(fd,1); close(fd); } if(error_to_file==true) { int fd=open("error.txt",O_CREAT|O_TRUNC|O_WRONLY,0644); if(fd<0) { fprintf(stderr,"No available file descriptors"); return(1); } dup2(fd,2); close(fd); } } else//all to file is true { int fd=open("output_and_error.txt",O_CREAT|O_TRUNC|O_WRONLY,0644); if(fd<0) { fprintf(stderr,"No available file descriptors"); return(1); } dup2(fd,2); dup2(fd,1); close(fd); } FILE *script_stream = fopen (script_name, "r"); if (! script_stream) error (1, errno, "%s: cannot open", script_name); command_stream_t command_stream = make_command_stream (get_next_byte, script_stream); command_t last_command = NULL; command_t command; if(time_travel) { struct dependency_graph* graph=create_graph(command_stream); int final_status=0; final_status=execute_graph(graph); } if(print_tree==true || time_travel==false) { while ((command = read_command_stream (command_stream))) { if (print_tree) { printf ("# %d\n", command_number++); print_command (command); } else { last_command = command; execute_command (command, time_travel); } } } return print_tree || !last_command ? 0 : command_status (last_command); }
void execute_pipe_command(command_t c) { // Create an array of two integers to store the pipe line file descriptors // fd[0] = Read things in from this file descriptor // fd[1] = Write things out from this file descriptor int fd[2]; // Establish the pipe if (pipe(fd) != 0) error(1, 0, "Failed to create pipe"); pid_t pid = fork(); int status; // If child process then close the read in portion of the pipe // Redirect stdout to the write descriptor of the pipe if (pid == 0) { close(fd[0]); // Redirect the write section of the pipe to standard out if (dup2(fd[1], STD_OUT) < 0) error(1, 0, "Failed to redirect write to stdout"); execute_command(c->u.command[0]); // Close the write portion of the pipe close(fd[1]); // Exit and return command 0's exit status _exit(c->u.command[0]->status); }else if (pid > 0) { pid_t pid2 = fork(); if (pid2 == 0) { // Close the write portion of the pipe close(fd[1]); // Redirect stdin to the read descriptor of the pipe if (dup2(fd[0], STD_IN) < 0) error(1, 0, "Failed to redirect stdin"); execute_command(c->u.command[1]); close(fd[0]); // Exit and return command 1's exit status _exit(c->u.command[1]->status); }else if (pid2 > 0) { // Close the pipe close(fd[0]); close(fd[1]); if (waitpid(pid2, &status, 0) < 0) abort(); c->status = WEXITSTATUS(status); }else error(1, 0, "Forked process failed"); }else error(1, 0, "Forked process failed"); }
/* Command to update the display with the current execution point. */ static void tui_update_command (const char *arg, int from_tty) { execute_command ("frame 0", from_tty); }
int main (int argc, char **argv) { int command_number = 1; bool print_tree = false; char const *profile_name = 0; program_name = argv[0]; for (;;) switch (getopt (argc, argv, "p:t")) { case 'p': profile_name = optarg; break; case 't': print_tree = true; break; default: usage (); break; case -1: goto options_exhausted; } options_exhausted:; // There must be exactly one file argument. if (optind != argc - 1) usage (); script_name = argv[optind]; FILE *script_stream = fopen (script_name, "r"); if (! script_stream) error (1, errno, "%s: cannot open", script_name); command_stream_t command_stream = make_command_stream (get_next_byte, script_stream); int profiling = -1; if (profile_name) { profiling = prepare_profiling (profile_name); if (profiling < 0) error (1, errno, "%s: cannot open", profile_name); } command_t last_command = NULL; command_t command; //timer starts struct timespec absolute; double start_time, prev_user_CPU, prev_sys_CPU; get_timer(&start_time, &prev_user_CPU, &prev_sys_CPU); while ((command = read_command_stream (command_stream))) { if (print_tree) { printf ("# %d\n", command_number++); print_command (command); } else { last_command = command; execute_command (command, profiling); } } //timer stops clock_gettime(CLOCK_REALTIME, &absolute); double absolute_time = absolute.tv_sec + (double)absolute.tv_nsec/1000000000.0; double end_time, current_user_CPU, current_sys_CPU; get_timer(&end_time, ¤t_user_CPU, ¤t_sys_CPU); double real_time = end_time - start_time; double userCPU = current_user_CPU-prev_user_CPU; double sysCPU = current_sys_CPU-prev_sys_CPU; pid_t pid = getpid(); char buffer[1024]; sprintf(buffer, "%f %f %.3f %.3f %d\n", absolute_time, real_time, userCPU, sysCPU, (int)pid); write(profiling, buffer, strlen(buffer)); return print_tree || !last_command ? 0 : command_status (last_command); }
int main (int argc, char **argv) { int command_number = 1; bool print_tree = false; bool time_travel = false; bool time_travel_limit = false; int num_of_processes =0; program_name = argv[0]; char c = ' '; for (;;) switch (getopt (argc, argv, "ptj")) { case 'p': print_tree = true;c = 'p'; break; case 't': time_travel = true; c = 't';break; case 'j': time_travel_limit = true; num_of_processes = atoi(argv[2]); c = 'j'; break; default: usage (); break; case -1: goto options_exhausted; } options_exhausted:; // There must be exactly one file argument. if (optind != argc - 1) { if (argc > 1 && c == 'j' && optind == argc-2) {} else { usage (); } } script_name = argv[argc - 1]; FILE *script_stream = fopen (script_name, "r"); if (! script_stream) error (1, errno, "%s: cannot open", script_name); command_stream_t command_stream = make_command_stream (get_next_byte, script_stream); command_t last_command = NULL; command_t command; while ((command = read_command_stream (command_stream))) { if (print_tree) { printf ("# %d\n", command_number++); print_command (command); } else { if (time_travel == false && time_travel_limit == false) { last_command = command; execute_command (command, time_travel); } } } if (time_travel == true) {execute(command_stream);} if (time_travel_limit == true) {execute_limit(command_stream, num_of_processes);} return print_tree || !last_command ? 0 : command_status (last_command); }
void execute_subshell_command (command_t c) { execute_command (c->u.subshell_command,time_travel); c->status = c->u.subshell_command->status; }
void controller_base::play_slice(bool is_delay_enabled) { display& gui = get_display(); CKey key; events::pump(); events::raise_process_event(); events::raise_draw_event(); slice_before_scroll(); // const theme::menu* const m = get_display().menu_pressed(); const button_loc& loc = get_display().menu_pressed(); const theme::menu* m = loc.first; if (m && (m == gui.access_troop_menu())) { map_location pressed_loc = gui.access_unit_press(loc.second); if (pressed_loc.valid() && !get_mouse_handler_base().is_moving() && !get_mouse_handler_base().is_recalling() && !get_mouse_handler_base().is_building() && !get_mouse_handler_base().is_card_playing()) { gui.scroll_to_tile(pressed_loc, display::WARP); events::mouse_handler::get_singleton()->select_hex(map_location(), false); // gui.select_hex(pressed_loc); // sound::play_UI_sound("select-unit.wav"); resources::units->find(pressed_loc)->set_selecting(); resources::screen->invalidate_unit(); // now, selectedHex_ is invalid, hide context menu. gui.goto_main_context_menu(); } } else if (m != NULL){ const SDL_Rect& menu_loc = m->location(get_display().screen_area()); if (m->is_context()) { // Is pressed menu a father menu of context-menu? const std::string& item = m->items()[loc.second]; std::vector<std::string> item2 = utils::split(item, ':'); if (item2.size() == 1) { // item2.push_back(item2[0]) is wrong way, resulting item2[1] is null string. item2.push_back(""); } size_t pos = item2[0].rfind("_m"); if (pos == item2[0].size() - 2) { // cancel current menu, and display sub-menu gui.hide_context_menu(NULL, true); const std::string item1 = item2[0].substr(0, pos); gui.get_theme().set_current_context_menu(get_display().get_theme().context_menu(item1)); show_context_menu(NULL, get_display()); } else { // execute one menu command pos = item2[0].rfind("_c"); if (pos == item2[0].size() - 2) { const std::string item1 = item2[0].substr(0, pos); // hotkey::execute_command(gui, hotkey::get_hotkey(item1).get_id(), this, -1, item2[1]); execute_command(hotkey::get_hotkey(item1).get_id(), -1, item2[1]); gui.hide_context_menu(NULL, true); } else { // hotkey::execute_command(gui, hotkey::get_hotkey(item2[0]).get_id(), this, -1, item2[1]); execute_command(hotkey::get_hotkey(item2[0]).get_id(), -1, item2[1]); } } } else { show_menu(m->items(), menu_loc.x+1, menu_loc.y + menu_loc.h + 1, false); } return; } int mousex, mousey; Uint8 mouse_flags = SDL_GetMouseState(&mousex, &mousey); bool was_scrolling = scrolling_; scrolling_ = handle_scroll(key, mousex, mousey, mouse_flags); get_display().draw(); // be nice when window is not visible // NOTE should be handled by display instead, to only disable drawing if (is_delay_enabled && (SDL_GetAppState() & SDL_APPACTIVE) == 0) { get_display().delay(200); } if (!scrolling_ && was_scrolling) { #if (defined(__APPLE__) && TARGET_OS_IPHONE) || defined(ANDROID) // swip result to scroll, don't update mouse hex. SDL_Event new_event; while(SDL_PeepEvents(&new_event, 1, SDL_GETEVENT, SDL_FINGERMOTION, SDL_FINGERMOTION) > 0) { posix_print("SDL_FINGERMOTION(discard), (x, y): (%u, %u), (dx, dy): (%i, %i)\n", new_event.tfinger.x, new_event.tfinger.y, new_event.tfinger.dx, new_event.tfinger.dy); }; #else // scrolling ended, update the cursor and the brightened hex get_mouse_handler_base().mouse_update(browse_); #endif } slice_end(); }
void execute_command (command_t c, bool time_travel) { int exitStatus; //use this variable to store return value of call to exec_simple_command //store the value into the command's status data member switch(c->type) { // AND, OR, SEQUENCE, and PIPE commands (passed into this function as parameter c) // store their arguments in their data member command_t *command[2] (located in the union --> u.command) // the way the command tree works, the pointers to commands stored in command[0] and command[1] // are simple commands --> to pass them into exec_simple_command, pass in the u.word data member of // the simple commands //c->(u.command[0])->(u.word) // AND: only attempt to execute the second argument if the first succeeds case AND_COMMAND: { if(c->u.command[0]->type == SIMPLE_COMMAND) { exitStatus = exec_simple_command(c->u.command[0]->u.word, c->u.command[0]); c->u.command[0]->status = exitStatus; } else { execute_command(c->u.command[0], 0); exitStatus = c->u.command[0]->status; } //if the first argument was successfully executed, try to execute the second if(exitStatus == 0) { if(c->u.command[1]->type == SIMPLE_COMMAND) { exitStatus = exec_simple_command(c->u.command[1]->u.word, c->u.command[1]); c->u.command[1]->status = exitStatus; } else { execute_command (c->u.command[1], 0); exitStatus = c->u.command[1]->status; } } //if the first argument of AND failed, immediately set c->status to the fail status //if the first argument succeeded, the second argument was executed, and c->status will be the //status of the second argument c->status = exitStatus; } break; // OR: only attempt to execute the second argument if the first argument fails case OR_COMMAND: { if(c->u.command[0]->type == SIMPLE_COMMAND) { exitStatus = exec_simple_command(c->u.command[0]->u.word, c->u.command[0]); c->u.command[0]->status = exitStatus; } else { execute_command(c->u.command[0], 0); exitStatus = c->u.command[0]->status; } //if the first argument was unsuccessful, execute the second if(exitStatus != 0) { if(c->u.command[1]->type == SIMPLE_COMMAND) { //c->u.command[1]->status = exec_simple_command(c->u.command[1]->u.word, c->u.command[1]); exitStatus = exec_simple_command(c->u.command[1]->u.word, c->u.command[1]); c->u.command[1]->status = exitStatus; } else { execute_command (c->u.command[1], 0); exitStatus = c->u.command[1]->status; } } //if the first argument of OR succeeded, immediately set c->status to the success status //if the first argument failed, the second argument was executed, and c->status will be the //status of the second argument c->status = exitStatus; } break; // SEQUENCE: will always have 2 arguments (decision when implementing in make_command_stream) // always execute the second argument even if the first one fails // sequence command status will be the status of the second argument case SEQUENCE_COMMAND: { if(c->u.command[0]->type == SIMPLE_COMMAND) { c->u.command[0]->status = exec_simple_command(c->u.command[0]->u.word, c->u.command[0]); } else { execute_command (c->u.command[0], 0); } if(c->u.command[1]->type == SIMPLE_COMMAND) { c->u.command[1]->status = exec_simple_command(c->u.command[1]->u.word, c->u.command[1]); } else { execute_command (c->u.command[1], 0); } c->status = c->u.command[1]->status; } break; // PIPE: regardless of whether or not the first argument succeeds or fails, the second argument //will execute. Therefore, the status of the pipe command is the same as the status of the second argument case PIPE_COMMAND: { int pid; int secondpid; int returnpid; int status; int saved_stdout = dup(1); int saved_stdin = dup(0); int pipefd[2]; pipe(pipefd); pid = fork(); if(pid == 0) // 0 if child process { close(pipefd[1]); dup2(pipefd[0], 0); if(c->u.command[1]->type == SIMPLE_COMMAND) { exec_simple_command(c->u.command[1]->u.word, c->u.command[1]); } else { execute_command (c->u.command[1], 0); } exit(c->u.command[1]->status); } else { secondpid = fork(); if (secondpid == 0) //0 if child process { close(pipefd[0]); dup2(pipefd[1], 1); if(c->u.command[0]->type == SIMPLE_COMMAND) { exec_simple_command(c->u.command[0]->u.word, c->u.command[0]); } else { execute_command (c->u.command[0], 0); } exit(c->u.command[0]->status); } else { close(pipefd[0]); close(pipefd[1]); dup2(saved_stdin, 0); dup2(saved_stdout, 1); returnpid = waitpid(-1, &status, 0); if(returnpid == secondpid) { waitpid(pid, &status, 0); c->u.command[0]->status = WEXITSTATUS(status); } if(returnpid == pid) { waitpid(secondpid, &status, 0); if(c->u.command[1]->type == SIMPLE_COMMAND) { c->u.command[1]->status = WEXITSTATUS(status); } else { execute_command (c->u.command[1], 0); } c->status = c->u.command[1]->status; } } } } break; case SIMPLE_COMMAND: c->status = exec_simple_command(c->u.word, c); break; case SUBSHELL_COMMAND: { int pid; // 0 if child process int status; int in; int out; int saved_stdout = dup(1); int saved_stdin = dup(0); pid = fork(); // child process if(pid == 0) { // REDIRECTIONS // restoring stdout with dup2 in case there are redirections if(c->input != 0) { in = open(c->input, O_CREAT | O_RDONLY, 0644); dup2(in, 0); close(in); } if(c->output != 0) { out = open(c->output, O_CREAT | O_TRUNC | O_WRONLY, 0622); dup2(out, 1); close(out); } execute_command(c->u.subshell_command, 0); exit(c->u.subshell_command->status); } // parent process else { dup2(saved_stdout, 1); dup2(saved_stdin, 0); // wait for child to terminate // store in variable status lots of info about the child process // pid_t waitpid(pid_t pid, int *status, int options); // The waitpid() system call suspends execution of the calling process // until a child specified by pid argument has changed state. waitpid(pid, &status, 0); //take the last 8 bits of variable status --> data that we want for the exit status c->status = WEXITSTATUS(status); } } break; default: { fprintf(stderr, "Invalid command type."); exit(1); } } }
/* NOTE: 1999-04-30 This is the asynchronous version of the command_loop function. The command_loop function will be obsolete when we switch to use the event loop at every execution of gdb. */ static void command_handler (char *command) { struct cleanup *old_chain; int stdin_is_tty = ISATTY (stdin); struct continuation_arg *arg1; struct continuation_arg *arg2; long time_at_cmd_start; #ifdef HAVE_SBRK long space_at_cmd_start = 0; #endif extern int display_time; extern int display_space; quit_flag = 0; if (instream == stdin && stdin_is_tty) reinitialize_more_filter (); old_chain = make_cleanup (null_cleanup, 0); /* If readline returned a NULL command, it means that the connection with the terminal is gone. This happens at the end of a testsuite run, after Expect has hung up but GDB is still alive. In such a case, we just quit gdb killing the inferior program too. */ if (command == 0) quit_command ((char *) 0, stdin == instream); time_at_cmd_start = get_run_time (); if (display_space) { #ifdef HAVE_SBRK char *lim = (char *) sbrk (0); space_at_cmd_start = lim - lim_at_start; #endif } execute_command (command, instream == stdin); /* Set things up for this function to be compete later, once the execution has completed, if we are doing an execution command, otherwise, just go ahead and finish. */ if (target_can_async_p () && target_executing) { arg1 = (struct continuation_arg *) xmalloc (sizeof (struct continuation_arg)); arg2 = (struct continuation_arg *) xmalloc (sizeof (struct continuation_arg)); arg1->next = arg2; arg2->next = NULL; arg1->data.longint = time_at_cmd_start; #ifdef HAVE_SBRK arg2->data.longint = space_at_cmd_start; #endif add_continuation (command_line_handler_continuation, arg1); } /* Do any commands attached to breakpoint we stopped at. Only if we are always running synchronously. Or if we have just executed a command that doesn't start the target. */ if (!target_can_async_p () || !target_executing) { bpstat_do_actions (&stop_bpstat); do_cleanups (old_chain); if (display_time) { long cmd_time = get_run_time () - time_at_cmd_start; printf_unfiltered (_("Command execution time: %ld.%06ld\n"), cmd_time / 1000000, cmd_time % 1000000); } if (display_space) { #ifdef HAVE_SBRK char *lim = (char *) sbrk (0); long space_now = lim - lim_at_start; long space_diff = space_now - space_at_cmd_start; printf_unfiltered (_("Space used: %ld (%c%ld for this command)\n"), space_now, (space_diff >= 0 ? '+' : '-'), space_diff); #endif } } }
void execute_command (command_t cmd, int time_travel) { /* FIXME: Replace this with your implementation. You may need to add auxiliary functions and otherwise modify the source code. You can also use external functions defined in the GNU C Library. */ // error (1, 0, "command execution not yet implemented"); int status; pid_t child; int fd[2]; switch (cmd->type) { case SIMPLE_COMMAND: child = fork(); if (!child) { //handle redirects then execution int fd_in, fd_out; if (cmd->input) { if ((fd_in = open(cmd->input, O_RDONLY, 0666)) == -1) error(1, 0, "cannot open input file!"); if (dup2(fd_in, 0) == -1) error(1, 0, "cannot do input redirect!"); } if (cmd->output) { if ((fd_out = open(cmd->output, O_WRONLY | O_CREAT, 0666)) == -1) error(1, 0, "cannot open output file!"); if (dup2(fd_out, 1) == -1) error(1, 0, "cannot do output redirect!"); } execvp(cmd->u.word[0], cmd->u.word); error(1,0,"cannot execute command"); } else if (child > 0) { waitpid(child, &status, 0); cmd->status = status; } else error(1, 0, "cannot create child process!"); break; case AND_COMMAND: //run left child command first, on its success, run right child command execute_command(cmd->u.command[0], time_travel); //printf("and status: %d\n", cmd->u.command[0]->status); if (cmd->u.command[0]->status == 0) { //run second command cmd2 execute_command(cmd->u.command[1], time_travel); cmd->status = cmd->u.command[1]->status; } else cmd->status = cmd->u.command[0]->status; break; case OR_COMMAND: //run left child command first, on its failure, run right child command execute_command(cmd->u.command[0], time_travel); //printf("or status: %d\n", cmd->u.command[0]->status); if (cmd->u.command[0]->status != 0) { //run second command cmd2 execute_command(cmd->u.command[1], time_travel); cmd->status = cmd->u.command[1]->status; } else cmd->status = cmd->u.command[0]->status; break; case PIPE_COMMAND: //create 2 processes for each, redirect output of cmd1 to input of cmd2 if (pipe(fd) == -1) error(1, 0, "cannot create pipe"); child = fork(); if (!child) { //child writes to pipe // printf("before close"); // close(fd[0]); // printf("before dup2"); if (dup2(fd[1], STDOUT_FILENO) == -1) error(1, 0, "cannot redirect output"); // printf("executing command %s", cmd->u.command[0]->u.word[0]); execute_command(cmd->u.command[0], time_travel); // printf("finishing command %s", cmd->u.command[0]->u.word[0]); close(fd[1]); exit(cmd->u.command[0]->status); } else if (child > 0) { //parent reads the pipe waitpid(child, &status, 0); cmd->u.command[0]->status = status; close(fd[1]); if (dup2(fd[0], STDIN_FILENO) == -1) error(1, 0, "cannot redirect input"); execute_command(cmd->u.command[1], time_travel); close(fd[0]); cmd->status = cmd->u.command[1]->status; //printf("status: %d\n", cmd->status); //exit(cmd->status); } else error(1, 0, "could not create child process!"); break; case SUBSHELL_COMMAND: execute_command(cmd->u.subshell_command, time_travel); break; case SEQUENCE_COMMAND: execute_command(cmd->u.command[0], time_travel); execute_command(cmd->u.command[1], time_travel); default: break; } }
enum command_control_type execute_control_command (struct command_line *cmd) { struct expression *expr; struct command_line *current; struct cleanup *old_chain = make_cleanup (null_cleanup, 0); struct value *val; struct value *val_mark; int loop; enum command_control_type ret; char *new_line; /* Start by assuming failure, if a problem is detected, the code below will simply "break" out of the switch. */ ret = invalid_control; switch (cmd->control_type) { case simple_control: /* A simple command, execute it and return. */ new_line = insert_args (cmd->line); if (!new_line) break; make_cleanup (free_current_contents, &new_line); execute_command (new_line, 0); ret = cmd->control_type; break; case continue_control: print_command_trace ("loop_continue"); /* Return for "continue", and "break" so we can either continue the loop at the top, or break out. */ ret = cmd->control_type; break; case break_control: print_command_trace ("loop_break"); /* Return for "continue", and "break" so we can either continue the loop at the top, or break out. */ ret = cmd->control_type; break; case while_control: { char *buffer = alloca (strlen (cmd->line) + 7); sprintf (buffer, "while %s", cmd->line); print_command_trace (buffer); /* Parse the loop control expression for the while statement. */ new_line = insert_args (cmd->line); if (!new_line) break; make_cleanup (free_current_contents, &new_line); expr = parse_expression (new_line); make_cleanup (free_current_contents, &expr); ret = simple_control; loop = 1; /* Keep iterating so long as the expression is true. */ while (loop == 1) { int cond_result; QUIT; /* Evaluate the expression. */ val_mark = value_mark (); val = evaluate_expression (expr); cond_result = value_true (val); value_free_to_mark (val_mark); /* If the value is false, then break out of the loop. */ if (!cond_result) break; /* Execute the body of the while statement. */ current = *cmd->body_list; while (current) { command_nest_depth++; ret = execute_control_command (current); command_nest_depth--; /* If we got an error, or a "break" command, then stop looping. */ if (ret == invalid_control || ret == break_control) { loop = 0; break; } /* If we got a "continue" command, then restart the loop at this point. */ if (ret == continue_control) break; /* Get the next statement. */ current = current->next; } } /* Reset RET so that we don't recurse the break all the way down. */ if (ret == break_control) ret = simple_control; break; } case if_control: { char *buffer = alloca (strlen (cmd->line) + 4); sprintf (buffer, "if %s", cmd->line); print_command_trace (buffer); new_line = insert_args (cmd->line); if (!new_line) break; make_cleanup (free_current_contents, &new_line); /* Parse the conditional for the if statement. */ expr = parse_expression (new_line); make_cleanup (free_current_contents, &expr); current = NULL; ret = simple_control; /* Evaluate the conditional. */ val_mark = value_mark (); val = evaluate_expression (expr); /* Choose which arm to take commands from based on the value of the conditional expression. */ if (value_true (val)) current = *cmd->body_list; else if (cmd->body_count == 2) current = *(cmd->body_list + 1); value_free_to_mark (val_mark); /* Execute commands in the given arm. */ while (current) { command_nest_depth++; ret = execute_control_command (current); command_nest_depth--; /* If we got an error, get out. */ if (ret != simple_control) break; /* Get the next statement in the body. */ current = current->next; } break; } case commands_control: { /* Breakpoint commands list, record the commands in the breakpoint's command list and return. */ new_line = insert_args (cmd->line); if (!new_line) break; make_cleanup (free_current_contents, &new_line); ret = commands_from_control_command (new_line, cmd); break; } case python_control: { eval_python_from_control_command (cmd); ret = simple_control; break; } default: warning (_("Invalid control type in canned commands structure.")); break; } do_cleanups (old_chain); return ret; }