/* * cdb_sync_command - process sync command */ bool cdb_sync_command(const char *cmd) { elog((Debug_print_qd_mirroring ? LOG : DEBUG5), "QDSYNC: %s", cmd); parseCmd(cmd); switch (cmdtype) { case SYNC_XLOG: cdb_sync_xlog(); break; case SYNC_POSITION_TO_END: cdb_position_to_end(); break; case SYNC_NEW_CHECKPOINT_LOC: cdb_new_checkpoint_loc(); break; case SYNC_SHUTDOWN_TOO_FAR_BEHIND: return true; case SYNC_CLOSE: cdb_close(); elog(LOG,"QDSYNC: master is closing..."); break; } return false; }
int main(int argc, char ** argv) { int pin = TINY4412_PWM0; float angle; float duty; if (argc == 3) { if (parseCmd(argc, argv, &pin, &angle) == -1) { return -1; } } else { angle = 90; printf("Usage:%s PWM[0~1] angle[0~180]\n", argv[0]); printf("Using default config: pin=PWM0 angle=%.2f\n", angle); } // 0度:0.5ms,45度:1ms,90度:1.5ms,135度:2.0ms,180度:2.5ms duty = 0.5 + (angle/45) * 0.5; duty = duty / SERVO_PERIOD_MS * 1000; // 千分比 if (PWMPlay(pin, SERVO_HZ, duty) == -1) { printf("Fail to output PWM\n"); } return 0; }
command_t read_command_stream (command_stream_t s) { int l=strlen(s->stream); char *start=s->stream+s->index; if (*start==ENDCHAR) { s->index=s->index+1; start++; } char *endptr=start; char c=*endptr; while (c != ENDCHAR && c!='\0') c=*++endptr; //////printf("%c",c); s->index=endptr - s->stream; //////printf("index: %d,len: %d\n",s->index,l); //if(debug) printf("read_stream %d(index,l) (%d, %d)::: \"%.*s\"\n", j++,s->index,l,endptr-start,start); return start<endptr ? parseCmd(start,endptr-1) : NULL; }
void Link::rx(void) { qint32 i; rxStream+= server.readAll(); QStringList cmds = rxStream.split(QRegExp("[\r\n]")); for (i=0; i<cmds.size()-1; i++) { if (cmds[i] == "ok") { succeeded = 1; emit completed(); emit success(); } else if (cmds[i].contains("error")) { succeeded = 0; emit completed(); if (cmds[i].section('=', 1).size()) emit error(cmds[i].section('=', 1)); emit error(); } else parseCmd(this, cmds[i]); } if (cmds.size() > 1) { rxStream.clear(); if (cmds.at(i).size()) // if string size != 0, there is a partial command leftover rxStream+= cmds.at(i); } }
void parseAll(int argc, char *argv[], svt_parser_t *parser) { if (argc > 0){ parseCmd(argc, argv, parser); }else{ parseStdin(parser); } }
static void macThread( void *pvParameters ) { int i; Primitive prim; for(;;){ while( xQueueReceive( macQ, &prim, portMAX_DELAY ) != pdPASS ); parseCmd((char*)prim.msg); } }
void HostCommunication::parseByte(char b) { buffer[currentByte++] = b; if (state == ParseHeader) { MICROFLO_DEBUG(this, DebugLevelVeryDetailed, DebugParseHeader); if (currentByte == sizeof(MICROFLO_GRAPH_MAGIC)) { if (memcmp(buffer, MICROFLO_GRAPH_MAGIC, sizeof(MICROFLO_GRAPH_MAGIC)) == 0) { MICROFLO_DEBUG(this, DebugLevelDetailed, DebugMagicMatched); const uint8_t cmd[] = { GraphCmdCommunicationOpen }; transport->sendCommand(cmd, sizeof(cmd)); state = ParseCmd; } else { MICROFLO_DEBUG(this, DebugLevelError, DebugMagicMismatch); state = Invalid; } currentByte = 0; } } else if (state == ParseCmd) { MICROFLO_DEBUG(this, DebugLevelVeryDetailed, DebugParseCommand); if (currentByte == MICROFLO_CMD_SIZE) { if (memcmp(buffer, MICROFLO_GRAPH_MAGIC, sizeof(MICROFLO_GRAPH_MAGIC)) == 0) { MICROFLO_DEBUG(this, DebugLevelDetailed, DebugMagicMatched); const uint8_t cmd[] = { GraphCmdCommunicationOpen }; transport->sendCommand(cmd, sizeof(cmd)); // already in ParseCmd state } else { parseCmd(); } currentByte = 0; } } else if (state == LookForHeader) { MICROFLO_DEBUG(this, DebugLevelVeryDetailed, DebugParseLookForHeader); if (b == MICROFLO_GRAPH_MAGIC[0]) { state = ParseHeader; buffer[0] = b; currentByte = 1; } else { currentByte = 0; } } else if (state == Invalid) { MICROFLO_DEBUG(this, DebugLevelError, DebugParserInvalidState); // try to recover currentByte = 0; state = LookForHeader; } else { MICROFLO_DEBUG(this, DebugLevelError,DebugParserUnknownState); // try to recover currentByte = 0; state = LookForHeader; } }
int main(int argc, char *argv[]){ char cmdLine[lineLen], **cmdArg; pid_t pid; int status, i, debug; debug = 0; i = 1; while (i<argc){ if (!strcmp(argv[i],"-d")) debug = 1; i++; } while (1){ printf("iShell> "); fgets(cmdLine,lineLen,stdin); cmdLine[strlen(cmdLine)-1] = '\0'; cmdArg = parseCmd(cmdLine); if (debug){ i = 0; while (cmdArg[i] != NULL){ printf("\t%d (%s)\n",i,cmdArg[i]); i++; } } if (strcmp(cmdArg[0],"exit") == 0){ if (debug) printf("exiting\n"); printf("Thank you for using iShell\n"); break; } else if (strcmp(cmdArg[0],"cd") == 0){ if (debug) printf("doing cd\n"); chdir(cmdArg[1] ? cmdArg[1] : "/root"); } else{ if (debug) printf("going to fork\n"); pid = fork(); if (pid != 0){ waitpid(pid,&status,0); } else{ status = execv(cmdArg[0],cmdArg); if (status){ printf("\tno such cmd (%s)\n",cmdArg[0]); return 1; } } } i = 0; while (cmdArg[i] != NULL) free(cmdArg[i++]); free(cmdArg); } return 0; }
cmd_line *parseCmdLine(char *s) /*to break up string by ';' and '\n' and pass that string to parseCmd*/ { char *saveptr=s; char *token; token = strtok_r(saveptr, ";\n", &saveptr); cmd_line *cml = make_cmdline(parseCmd(token)); cmd_line *f = cml; while(token != NULL){ token = strtok_r(NULL, ";\n", &saveptr); if(token ==NULL){ return f; } if((strcmp(token, " ") == 0) || (strcmp(token, "\t") == 0)){ continue; }else { cml->next = make_cmdline(parseCmd(token)); cml = cml->next; } } return f; }
/** * Displays a command line and processes the commands entered. * * \retval 0 stdin was closed. * \retval 2 The user typed exit or quit. */ int Boomerang::cmdLine() { char line[1024]; printf("boomerang: "); fflush(stdout); while (fgets(line, sizeof(line), stdin)) { char **argv; int argc = splitLine(line, &argv); if (parseCmd(argc, (const char **)argv) == 2) return 2; printf("boomerang: "); fflush(stdout); } return 0; }
void parseMultiCmd(const char **strptr) { parseCmd(strptr); Token nextToken = peekToken(*strptr); switch (nextToken) { case IDENTIFIER: parseMultiCmd(strptr); break; case END: break; default: PARSE_ASSERT(0); } }
//////////////////////////////////////////////////////////////////////////////// // Register myself with the server int registerClient( Folder *dir, int sock ) { int nbytes; // Number of bytes char buffer[ MAXBUFSIZE ]; // Buffer printf( "$ Sending name '%s'\n", dir->name ); sprintf( buffer, "%s", dir->name ); nbytes = write( sock, dir->name, MAXBUFSIZE ); ERROR( nbytes < 0 ); bzero( buffer, MAXBUFSIZE ); nbytes = read( sock, buffer, MAXBUFSIZE ); ERROR( nbytes < 0 ); return parseCmd( buffer ); } // registerClient( )
int main(int argc, const char * argv[]) { char cmd[100]; char* params[MAX_PARAMS]; pid_t pid; while (1) { char cwd[MAX_CWD_SIZE]; // Print the current working directory getcwd(cwd, MAX_CWD_SIZE); printf(BOLDGREEN "%s $ " RESET, cwd); // read command if (fgets(cmd, sizeof(cmd), stdin) == NULL) break; // remove any trailing end of line characters if (cmd[strlen(cmd)-1] == '\n') { cmd[strlen(cmd)-1] = '\0'; } if (strcmp(cmd, "exit") == 0) { printf("Exiting shell..\n"); return 0; } pid = fork(); if (pid == -1) { perror("Fork error"); exit(1); } else if (pid == 0) { // child process parseCmd(cmd, params); execvp(cmd, params); printf("Command not found!\n"); return 0; } else { // wait for child process int childStatus; waitpid(pid, &childStatus, 0); } } return 0; }
void IrcLayer::ircParse(QByteArray data) { QString line=m_codec->toUnicode(data); line.remove(*mircColors); line.remove(*mircShit); if(prRegexes["cmd"].exactMatch(line)) { QHash<QString, QString> data; data["nick"]=prRegexes["cmd"].cap(1); // nick data["ident"]=prRegexes["cmd"].cap(2); // ident data["host"]=prRegexes["cmd"].cap(3); // host parseCmd(prRegexes["cmd"].cap(4),data); } else if(prRegexes["resp"].exactMatch(line)) { QHash<QString, QString> data; data["target"]=prRegexes["resp"].cap(2); parseResp(prRegexes["resp"].cap(1).toInt(), prRegexes["resp"].cap(3),data); } }
int tcmd_exec(const char *cmdline, void (*reportCB)(void *), jmp_buf *jbuf) { #define MAX_ARGS 30 char cmdbuf[2048]; char *argv[MAX_ARGS]; /* max 30 arguments */ int argc = parseCmd(cmdline, cmdbuf, argv, MAX_ARGS); #else static void cmdReplyFunc_readThermal(void *buf) { A_UINT8 *reply = (A_UINT8*)buf; TC_CMDS tCmdReply; tCmdReply.hdr.u.parm.length = *(A_UINT16 *)&(reply[0]); tCmdReply.hdr.u.parm.version = (A_UINT8)(reply[2]); memcpy((void*)&(tCmdReply.buf), (void*)(buf+4), tCmdReply.hdr.u.parm.length); printf("chip thermal value:%d\n", tCmdReply.buf[0]); // printf("reply len %d ver %d act %d buf %x %x %x %x %x %x %x %x\n", tCmdReply.hdr.u.parm.length, tCmdReply.hdr.u.parm.version, tCmdReply.hdr.act, tCmdReply.buf[0], tCmdReply.buf[1],tCmdReply.buf[2], tCmdReply.buf[3], tCmdReply.buf[4],tCmdReply.buf[5], tCmdReply.buf[6], tCmdReply.buf[7]); return; }
int receiveProgramSize(socket) { char buf[1024] ={0}; int bytes_read; int arg_pos; int size; bytes_read = recvline(socket, buf, sizeof(buf)-1); if (bytes_read <= 0) _terminate(4); arg_pos = parseCmd(PRGM_SIZE_CMD, buf); if (!arg_pos) { invalid_command(); _terminate(5); } size = strn2int(buf+arg_pos, MAX_ARG_SIZE); return size; }
void DecodeCallBack::onTransportFailure (FailureMode f) { { #ifdef THREADING_WORKAROUND CriticalSection::Lock cs_lock (cs); #endif printTimestamp (); iprintlf(II("*** HCI TRANSPORT FAILED *** (failureMode: ")); printByValue(transportErrors_d, f, 16, "Unknown transport error"); iprintlf(II(")")); #ifdef DONT_COMPLETELY_SCREW_UP_ANYONE_EXPECTING_NORMAL_END_OF_LINE_TERMINATORS printlf("\n"); #else printf ("\r"); printlfOnly ("\n"); fflush (stdout); } if (auto_rawlog) { parseCmd("rawlog", true); } #endif }
//////////////////////////////////////////////////////////////////////////////// // Funciton to connect and register and all that nonsense void connectPlease( Folder *dir, int sock ) { int nbytes; // Number of bytes char buffer[ MAXBUFSIZE ]; // Buffer nbytes = write( sock, "CONNECT", MAXBUFSIZE ); ERROR( nbytes < 0 ); bzero( buffer, MAXBUFSIZE ); nbytes = read( sock, buffer, MAXBUFSIZE ); ERROR ( nbytes < 0 ); switch ( parseCmd( buffer ) ) { case CONNECT: { printf( "$ Connection Established\n" ); switch ( registerClient( dir, sock ) ) { case FAILURE: { printf( "$ There is already a user with the name '%s' on the server.\n", dir->name ); close( sock ); exit( EXIT_SUCCESS ); } case SUCCESS: { printf( "$ You have been connected as %s\n", dir->name ); sendList( dir, sock ); break; } } break; } default: { printf( "$ Error in registering\n" ); } } } // connectionPlease( )
static int excute(int socket, char* cmd){ int argsCnt = 0, i = 0; short ret = -1; char reply[REPLY_LEN]; if ((argsCnt = parseCmd(cmd)) < 0) goto done; for (i = 0; i < sizeof(cmds)/sizeof(cmds[0]); ++i){ if (!strcmp(cmds[i].cmd_name, cmdArgs[0])){ if (cmds[i].cmd_args_cnt != argsCnt) { debug_sys("cmds args is not map"); goto done; } else { ret = cmds[i].excute(cmdArgs + 1, reply); break; } } } done: return writex(socket, (char*)&ret, 2); }
/* return true: up return false: quit */ bool Tracker::enterDebugerTile(UI tileId){ if (tileId < 0 || tileId >= tileProbes.size()) { cout << "No such tile with ID: " << tileId << ". Tile id from 0~" << tileProbes .size()-1<< endl; return true; } string cmd; while (true) { cout << "NoC.Tile_"<<tileId<<">"; vector<string> cmd = parseCmd(); if (cmd.size() == 0) continue; if (strcasecmp(cmd[0].c_str(), "up") == 0) return true; else if (strcasecmp(cmd[0].c_str(), "help")==0) printDebugerHelp(1, cout); else if (strcasecmp(cmd[0].c_str(), "quit")==0) return false; } return true; }
command_t parseCmd(char *start, char *end) { if (start>end/* || iters++>MAXITER*/) return NULL; //trim the start and end pointers start=skipWs(start); if (*start=='\0') return NULL; while (*end == ' ' || *end == '\t' || *end == '\n') { end--; } if (debug) printf("parsing: \"%.*s\" start = \'%c\' end = \'%c\'\n", end-start+1, start, *start, *end); command_t t = (command_t) checked_malloc(sizeof(struct command)); char *ptr = start; //char *op = findNextOperator(ptr); char *op = strpbrk(skipSubshell(ptr), ";$*|"); char *next = op; ////printf("parsing: start = %c op = %c next = %c \n", *ptr, *op, *next); while (next && next <= end) { char * prec = ";$*|"; int opPrec = strchr(prec, *op) - prec; int nextPrec = strchr(prec, *next) - prec; //printf("parsing: [while] opPrec = %d nextPrec = %d \n", opPrec, nextPrec); if (((opPrec == 1 || opPrec == 2) && (nextPrec == 1 || nextPrec == 2)) || (nextPrec < opPrec)) { op = next; } //printf("parsing: [while] start = %c op = %c next = %c \n", *ptr, *op, *next); //next = findNextOperator(++next); next = strpbrk(skipSubshell(++next), ";$*|"); } if (op && op<end) { // if operator in expression //////printf("op: %c\n",*op); switch(*op) { case ';': t->type=SEQUENCE_COMMAND; break; case '$': t->type=OR_COMMAND; break; case '*': t->type=AND_COMMAND; break; case '|': t->type=PIPE_COMMAND; break; default: error(1,0,"illegal operator detected"); //should not get here break; } //printf("\ncomplex command type%d: %.*s,%.*s\n", t->type, op-start, start,end-op,op+1); //t->u.command=(command_t *) checked_malloc(sizeof(command_t)*2); t->u.command[0]=parseCmd(start,op-1); t->u.command[1]=parseCmd(op+1,end); } else if (*start == '(') { //if subshell //printf("subshell command\n"); ptr = skipSubshell(ptr); t->type=SUBSHELL_COMMAND; t->u.subshell_command=(command_t) checked_malloc(sizeof(command_t)); t->u.subshell_command=parseCmd(start+1,ptr-1); } else { //simple command with no op and no subshell //if (debug) printf("Building simple command\n"); t->type=SIMPLE_COMMAND; int wdct=0;//word count tracker //construct the simple command struct from str - check for redirections char* s = start; char* e; while (s) { if(*s == '<') { s = nextWordStart(s, end); e = currWordEnd(s, end); size_t wsize = e-s+1; t->input=(char *) checked_malloc(wsize+1); memcpy(t->input,s,wsize); t->input[wsize]='\0'; if(debug) printf("Building segments: \"%.*s\" -> \'%s\'\n", e-s+1, s, t->input); } else if(*s == '>') { s = nextWordStart(s, end); e = currWordEnd(s, end); size_t wsize = e-s+1; t->output=(char *) checked_malloc(wsize+1); memcpy(t->output,s,wsize); t->output[wsize]='\0'; if(debug) printf("Building segments: \"%.*s\" -> \'%s\'\n", e-s+1, s, t->output); } else { e = currWordEnd(s, end); size_t wsize = e-s+1; size_t asize = sizeof(char*) * (wdct+2); t->u.word = (char **) checked_realloc(t->u.word, asize); t->u.word[wdct] = (char *) checked_malloc(wsize+1); memcpy(t->u.word[wdct],s,wsize); t->u.word[wdct][wsize]='\0'; wdct++; if(debug) printf("Building segments: \"%.*s\" -> \'%s\'\n", e-s+1, s, t->u.word[wdct-1]); } s = nextWordStart(e, end); } *(t->u.word+wdct)=NULL; } return t; }
int main(int argc, char *argv[], char *envp[]){ char cmdLine[lineLen], **cmdArg; char hist[numRec][lineLen]; char *scratch, *ptr, path[numPath][lineLen]; char *fileName, *fileName1, *fileName2; pid_t pid, pid1, pid2; int oldIn, newIn, oldOut, newOut; int status, status1, status2, i, j, debug, histLen, histStart, numEnvVar; int pipeFound, pipeArg, fd[2]; struct EnvVar myEnvVar[maxEnvVar]; /* set history queue */ histLen = 0; histStart = 0; /* create array of structs myEnvVar */ scratch = (char*)malloc(sizeof(char)*lineLen); if (scratch == NULL){ perror("scratch"); exit(1); } i = 0; while (envp[i] != NULL){ if (strlen(envp[i])+1 > lineLen){ printf("env var too long\n"); return 1; } strcpy(scratch,envp[i]); ptr = strtok(scratch,"="); myEnvVar[i].name = (char*)malloc(sizeof(char)*(strlen(ptr)+1)); if (myEnvVar[i].name == NULL){ perror("myEnvVar[i].name"); exit(1); } strcpy(myEnvVar[i].name,ptr); ptr = strtok(NULL," "); myEnvVar[i].value = (char*)malloc(sizeof(char)*(strlen(ptr)+1)); if (myEnvVar[i].value == NULL){ perror("myEnvVar[i].value"); exit(1); } strcpy(myEnvVar[i].value,ptr); ++i; } numEnvVar = i; free(scratch); debug = 0; i = 1; while (i<argc){ if (!strcmp(argv[i],"-d")) debug = 1; i++; } while (1){ printf("iShell> "); fgets(cmdLine,lineLen,stdin); cmdLine[strlen(cmdLine)-1] = '\0'; if (strcmp(cmdLine,"") == 0) continue; if (histLen<10) ++histLen; else histStart = ++histStart%10; strcpy(hist[(histStart+histLen-1)%10],cmdLine); cmdArg = parseCmd(cmdLine); if (debug){ i = 0; while (cmdArg[i] != NULL){ printf("\t%d (%s)\n",i,cmdArg[i]); i++; } } if (cmdArg[0] == NULL){ continue; } else if (strcmp(cmdArg[0],"exit") == 0){ if (debug) printf("exiting\n"); printf("Thank you for using iShell\n"); break; } else if (strcmp(cmdArg[0],"env") == 0){ if (debug) printf("listing environment variables\n"); /* Output redirection */ newOut = -1; if (cmdArg[1] != NULL && strcmp(cmdArg[1],">") == 0){ if (cmdArg[2] != NULL){ fflush(stdout); oldOut = dup(1); newOut = open(cmdArg[2], O_WRONLY | O_CREAT); if (newOut >= 0){ dup2(newOut, 1); close(newOut); } else{ printf("unable to open file for output\n"); } } } for(i=0;i<numEnvVar;++i) printf("env var %d:\t%s=%s\n",i,myEnvVar[i].name,myEnvVar[i].value); /* Reset stdout */ if (newOut >= 0){ dup2(oldOut, 1); close(oldOut); } } else if (strcmp(cmdArg[0],"setenv") == 0){ if (debug) printf("setting environment variable\n"); if (cmdArg[1] == NULL || cmdArg[2] == NULL){ printf("syntax: setenv variable value\n"); continue; } i = 0; while (i < numEnvVar){ if (strcmp(myEnvVar[i].name,cmdArg[1]) == 0){ myEnvVar[i].value = (char*)realloc(myEnvVar[i].value, sizeof(char)* (strlen(cmdArg[2])+1)); if (myEnvVar[i].value == NULL){ perror("old myEnvVar[i].value"); exit(1); } strcpy(myEnvVar[i].value,cmdArg[2]); break; } ++i; } /* make new environment variable */ if (i == numEnvVar){ myEnvVar[i].name = (char*)malloc(sizeof(char)*(strlen(cmdArg[1])+1)); if (myEnvVar[i].name == NULL){ perror("new myEnvVar[i].name"); exit(1); } strcpy(myEnvVar[i].name,cmdArg[1]); myEnvVar[i].value = (char*)malloc(sizeof(char)*(strlen(cmdArg[2])+1)); if (myEnvVar[i].value == NULL){ perror("new myEnvVar[i].value"); exit(1); } strcpy(myEnvVar[i].value,cmdArg[2]); numEnvVar++; } } else if (strcmp(cmdArg[0],"unsetenv") == 0){ if (debug) printf("removing environment variable\n"); if (cmdArg[1] == NULL){ printf("syntax: unsetenv variable\n"); continue; } i = 0; while (i < numEnvVar){ if (strcmp(myEnvVar[i].name,cmdArg[1]) == 0) break; ++i; } if (i == numEnvVar){ printf("env var not found\n"); } else{ while (i < numEnvVar-1){ myEnvVar[i].name = (char*)realloc(myEnvVar[i].name, sizeof(char)* (strlen(myEnvVar[i+1].name)+1)); if (myEnvVar[i].name == NULL){ perror("myEnvVar[i].name"); exit(1); } strcpy(myEnvVar[i].name,myEnvVar[i+1].name); myEnvVar[i].value = (char*)realloc(myEnvVar[i].value, sizeof(char)* (strlen(myEnvVar[i+1].value)+1)); if (myEnvVar[i].value == NULL){ perror("myEnvVar[i].value"); exit(1); } strcpy(myEnvVar[i].value,myEnvVar[i+1].value); ++i; } free(myEnvVar[i].name); free(myEnvVar[i].value); numEnvVar--; } } else if (strcmp(cmdArg[0],"cd") == 0){ if (debug) printf("changing working directory\n"); if (chdir(cmdArg[1] ? cmdArg[1] : "/root") == 0){ /* update CWD */ i = 0; while (i < numEnvVar){ if (strcmp(myEnvVar[i].name, "PWD") == 0){ myEnvVar[i].value = (char*)realloc(myEnvVar[i].value, sizeof(char)*lineLen); if (myEnvVar[i].value == NULL){ perror("myEnvVar[i].value"); exit(1); } getcwd(myEnvVar[i].value, lineLen-1); break; } ++i; } } } else if (strcmp(cmdArg[0],"history") == 0){ if (debug) printf("displaying the last ten commands\n"); /* Output redirection */ newOut = -1; if (cmdArg[1] != NULL && strcmp(cmdArg[1],">") == 0){ if (cmdArg[2] != NULL){ fflush(stdout); oldOut = dup(1); newOut = open(cmdArg[2], O_WRONLY | O_CREAT); if (newOut >= 0){ dup2(newOut, 1); close(newOut); } else{ printf("unable to open file for output\n"); } } } for(i=0;i<histLen;++i) printf("%s\n", hist[(histStart+i)%10]); /* Reset stdout */ if (newOut >= 0){ dup2(oldOut, 1); close(oldOut); } } else{ /* MINIX commands */ /* first make a list of paths */ /* get PATH variable value */ i = 0; while (i < numEnvVar){ if (strcmp(myEnvVar[i].name, "PATH") == 0){ scratch = (char*)malloc( sizeof(char)*(strlen(myEnvVar[i].value)+1)); if (scratch == NULL){ perror("scratch"); exit(1); } strcpy(scratch,myEnvVar[i].value); break; } ++i; } /* obtain and save individual paths */ i = 0; ptr = strtok(scratch,":"); while (ptr != NULL){ strcpy(path[i], ptr); ++i; ptr = strtok(NULL,":"); } free(scratch); /* a list of paths is now saved in path[] */ /* is there a pipe? */ pipeFound = 0; i = 1; /* cmdArg[0] cannot be '|' */ while (cmdArg[i] != NULL){ if (strcmp(cmdArg[i], "|") == 0){ pipeFound = 1; pipeArg = i; break; } i++; } if (pipeFound){ /* there is a pipe */ if (debug) printf("Found pipe: (%d)\n", pipeArg); if (cmdArg[i+1] == NULL){ /* there is nothing following the '|' */ if (debug) printf("| without command\n"); continue; } cmdArg[pipeArg] = NULL; /* locate command files */ fileName1 = (char*)malloc(sizeof(char)*lineLen); if (fileName1 == NULL){ perror("fileName1"); exit(1); } i = 0; while (i < numPath && path[i] != NULL){ strcpy(fileName1, strcat(strcat(path[i],"/"),cmdArg[0])); if (access(fileName1, F_OK) == 0){ /* found a good path */ if (debug) printf("%s\n", fileName1); break; } i++; } if (i==numPath || path[i]==NULL){ printf("%s not found\n",cmdArg[0]); free(fileName1); continue; } fileName2 = (char*)malloc(sizeof(char)*lineLen); if (fileName2 == NULL){ perror("fileName2"); exit(1); } i = 0; while (i < numPath && path[i] != NULL){ strcpy(fileName2, strcat(strcat(path[i],"/"),cmdArg[pipeArg+1])); if (access(fileName2, F_OK) == 0){ /* found a good path */ if (debug) printf("%s\n", fileName2); break; } i++; } if (i==numPath || path[i]==NULL){ printf("%s not found\n",cmdArg[pipeArg+1]); free(fileName1); free(fileName2); continue; } pipe(fd); pid2 = fork(); if (pid2 == 0){ /* I am the child for the 2nd part of pipe */ /* redirect I/O for pipe */ close(fd[1]); /* close pipe output */ close(0); /* close stdin */ dup(fd[0]); /* dup pipe input to stdin */ close(fd[0]); /* close pipe input */ /* check for output redirection */ i = pipeArg + 2; while (cmdArg[i] != NULL){ if (strcmp(cmdArg[i], ">") == 0){ /* redirect output */ if (debug) printf("attempting to redirect output\n"); if (cmdArg[i+1] != NULL){ newOut = open(cmdArg[i+1], O_WRONLY | O_CREAT); if (newOut >= 0){ close(1); dup(newOut); close(newOut); } else{ if (debug) printf("couldn't open output file\n"); } } else { if (debug) printf ("> without filename\n"); break; } cmdArg[i] = NULL; } i++; } /* ready to execute 2nd part of pipe */ status2 = execv(fileName2, cmdArg + pipeArg+1); } else{ pid1 = fork(); if (pid1 == 0){ /* I am the child for the 1st part of the pipe */ /* redirect I/O for pipe */ close(fd[0]); /* close pipe input */ close(1); /* close stdout */ dup(fd[1]); /* dup pipe output to stdout */ close(fd[1]); /* close pipe output */ /* check for input redirection */ i = 1; while (cmdArg[i] != NULL){ if (strcmp(cmdArg[i], "<") == 0){ /* redirect input */ if (debug) printf("attempting to redirect input\n"); if (cmdArg[i+1] != NULL){ newIn = open(cmdArg[i+1], O_RDONLY | O_CREAT); if (newIn >= 0){ close(0); dup(newIn); close(newIn); } else{ if (debug) printf("couldn't open input file\n"); } } else { if (debug) printf ("< without filename\n"); break; } cmdArg[i] = NULL; } i++; } /* ready to execute 1st part of pipe */ status1 = execv(fileName1, cmdArg); } else{ /* I am the parent process */ close(fd[0]); close(fd[1]); waitpid(pid1,&status1,0); } waitpid(pid2,&status2,0); } /* free memory */ free(fileName1); free(fileName2); } else{ /* no pipe */ /* check for file */ fileName = (char*)malloc(sizeof(char)*lineLen); if (fileName == NULL){ perror("fileName"); exit(1); } i = 0; while (i < numPath && path[i] != NULL){ strcpy(fileName, strcat(strcat(path[i],"/"),cmdArg[0])); if (access(fileName, F_OK) == 0){ if (debug) printf("going to fork\n"); pid = fork(); if (pid != 0){ waitpid(pid,&status,0); } else{ /* I am the child process */ /* I/O Redirection */ j = 1; while (cmdArg[j] != NULL){ if (strcmp(cmdArg[j], "<") == 0){ /* redirect input */ if (debug) printf ("attempting to redirect input\n"); if (cmdArg[j+1] != NULL){ newIn = open(cmdArg[j+1], O_RDONLY | O_CREAT); if (newIn >= 0){ close(0); dup(newIn); close(newIn); } else{ if (debug) printf ("couldn't open input file\n"); } } else{ /* bad syntax, abort I/O redirection */ if (debug) printf ("< without filename\n"); break; } cmdArg[j] = NULL; } else if (strcmp(cmdArg[j], ">") == 0){ /* redirect output */ if (debug) printf("attempting to redirect output\n"); if (cmdArg[j+1] != NULL){ newOut = open(cmdArg[j+1], O_WRONLY | O_CREAT); if (newOut >= 0){ close(1); dup(newOut); close(newOut); } else{ if (debug) printf ("couldn't open output file\n"); } } else{ /* bad syntax, abort I/O redirection */ if (debug) printf ("> without filename\n"); break; } cmdArg[j] = NULL; } j++; } status = execv(fileName,cmdArg); } break; } i++; } if (i == numPath || path[i] == NULL) printf("command not found\n"); /* free memory */ free(fileName); } } i = 0; while (cmdArg[i] != NULL) free(cmdArg[i++]); free(cmdArg); } for(i=0;i<numEnvVar;++i){ free(myEnvVar[i].name); free(myEnvVar[i].value); } return 0; }
GLDEF_C void CallTestsL() // // Do all tests // { TInt r = TTest::Init(); test_KErrNone(r); TChar drvch0 = TTest::DefaultDriveChar(); TChar drvch1 = 0; TChar drvch2 = 0; TInt drive0; TInt drive1; TInt drive2; const TInt KMaxArgs = 4; TPtrC argv[KMaxArgs]; TInt argc = TTest::ParseCommandArguments(argv, KMaxArgs); if (argc > 1) drvch0 = User::UpperCase(argv[1][0]); if (argc > 2) drvch1 = User::UpperCase(argv[2][0]); if (argc > 3) drvch2 = User::UpperCase(argv[3][0]); r = TheFs.CharToDrive(drvch0, drive0); test_KErrNone(r); if (TheFs.IsValidDrive(drive0)) MountTestFileSystem(drive0); else test.Printf(_L("Unable to mount test file system\n")); r = parseCmd(drvch1, drvch2); if (r != KErrNone) { UnmountFileSystem(drive0); User::Panic(_L("USER ABORT"), 0); } r = TheFs.CharToDrive(drvch1, drive1); test_KErrNone(r); r = TheFs.CharToDrive(drvch2, drive2); test_KErrNone(r); r = TheFs.FileSystemName(gFsName1, drive1); test_Value(r, r == KErrNone || r == KErrNotFound); r = TheFs.FileSystemName(gFsName2, drive2); test_Value(r, r == KErrNone || r == KErrNotFound); gDataLock.CreateLocal(); if (drive1 == drive2) { // !!! Disable platform security tests until we get the new APIs // if (User::Capability() & KCapabilityRoot) // CheckMountLFFS(TheFs, drvch1); test.Printf(_L("Using drive %c: (%S)\n"), (TUint)drvch1, &gFsName1); if (r == KErrNone) { test.Next(_L("Test with drive asynchronous")); RemountFileSystem(drive1, EFalse); testAsyncAccess(drvch1, drvch1); } if (r == KErrNone) { test.Next(_L("Test with drive synchronous")); RemountFileSystem(drive1, ETrue); testAsyncAccess(drvch1, drvch1); } } else { // !!! Disable platform security tests until we get the new APIs /* if (User::Capability() & KCapabilityRoot) { CheckMountLFFS(TheFs, drvch1); CheckMountLFFS(TheFs, drvch2); } */ test.Printf(_L("Using drives %c: (%S) and %c: (%S)\n"), (TUint)drvch1, &gFsName1, (TUint)drvch2, &gFsName2); #if !defined(TEST_ASYNC_IN_THREAD) if (r == KErrNone) { test.Next(_L("Test async r/w with both drives async")); RemountFileSystem(drive1, EFalse); RemountFileSystem(drive2, EFalse); testAsyncAccess(drvch1, drvch2); } if (r == KErrNone) { test.Next(_L("Test async r/w with 1st drive sync and 2nd async")); RemountFileSystem(drive1, ETrue); RemountFileSystem(drive2, EFalse); testAsyncAccess(drvch1, drvch2); } if (r == KErrNone) { test.Next(_L("Test async r/w with 1st drive async and 2nd sync")); RemountFileSystem(drive1, EFalse); RemountFileSystem(drive2, ETrue); testAsyncAccess(drvch1, drvch2); } if (r == KErrNone) { test.Next(_L("Test async r/w with both drives sync")); RemountFileSystem(drive1, ETrue); RemountFileSystem(drive2, ETrue); testAsyncAccess(drvch1, drvch2); } #else if (r == KErrNone) { test.Next(_L("Test async r/w with both drives asynchronous")); RemountFileSystem(drive1, EFalse); RemountFileSystem(drive2, EFalse); r = testThreads(testAsyncAccess, drvch1, drvch2); } if (r == KErrNone) { test.Next(_L("Test async r/w with one drive sync and one async")); RemountFileSystem(drive1, ETrue); RemountFileSystem(drive2, EFalse); r = testThreads(testAsyncAccess, drvch1, drvch2); } if (r == KErrNone) { test.Next(_L("Test async r/w with both drives synchronous")); RemountFileSystem(drive1, ETrue); RemountFileSystem(drive2, ETrue); r = testThreads(testAsyncAccess, drvch1, drvch2); } #endif #if defined(TEST_SYNC_IN_THREAD) if (r == KErrNone) { test.Next(_L("Test sync r/w with both drives asynchronous")); RemountFileSystem(drive1, EFalse); RemountFileSystem(drive2, EFalse); r = testThreads(testSyncAccess, drvch1, drvch2); } if (r == KErrNone) { test.Next(_L("Test sync r/w with one drive sync and one async")); RemountFileSystem(drive1, ETrue); RemountFileSystem(drive2, EFalse); r = testThreads(testSyncAccess, drvch1, drvch2); } if (r == KErrNone) { test.Next(_L("Test sync r/w with both drives synchronous")); RemountFileSystem(drive1, ETrue); RemountFileSystem(drive2, ETrue); r = testThreads(testSyncAccess, drvch1, drvch2); } #endif } gDataLock.Close(); UnmountFileSystem(drive0); test_Value(r, r == 0); }
void executeProgram(Program* program) { Stack stack; int arg_pos; initStack(&stack, program->size * 16, MAX_ARG_SIZE); if(stack.elements == NULL) return; program->lineNumber = 0; while(program->lineNumber < program->size) { char* line; line = &program->lines[program->lineNumber*MAX_LINE_SIZE]; if((arg_pos = parseCmd(PUSH_CMD, line)) > 0) { pushElement(&stack, line+arg_pos); program->lineNumber++; } else if((arg_pos = parseCmd(POP_CMD, line)) > 0) { char* element; int len; element = (char *) popElement(&stack); len = strnlen(element, MAX_ARG_SIZE); memset(element, 0, len); program->lineNumber++; } else if((arg_pos = parseCmd(ADD_CMD, line)) > 0) { int a, b, ret; char *a_str; char *a_element; char *b_element; int len; a_element = popElement(&stack); b_element = popElement(&stack); a = strn2int(a_element, MAX_ARG_SIZE); b = strn2int(b_element, MAX_ARG_SIZE); a += b; a_str = itoaB10(a); len = strnlen(a_element, MAX_ARG_SIZE); memset(a_element, 0, len); len = strnlen(b_element, MAX_ARG_SIZE); memset(b_element, 0, len); len = strlen(a_str); pushElement(&stack, a_str); ret = deallocate(a_str, len); if (ret != 0) _terminate(11); program->lineNumber++; } else if((arg_pos = parseCmd(PRINT_CMD, line)) > 0) { int ret, len; char *element; element = (char *) popElement(&stack); ret = transmit_all(STDOUT, element, strnlen(element, MAX_ARG_SIZE)); if (ret != 0) _terminate(14); ret = transmit_all(STDOUT, NEWLINE, strnlen(NEWLINE, MAX_ARG_SIZE)); if (ret != 0) _terminate(15); len = strnlen(element, MAX_ARG_SIZE); memset(element, 0, len); program->lineNumber++; } else if((arg_pos = parseCmd(COPY_CMD, line)) > 0) { int copy_num; int ret, i; copy_num = strn2int(line+arg_pos, MAX_ARG_SIZE); if(copy_num < 1) { program->lineNumber++; continue; } char *element; element = popElement(&stack); for(i=0; i<copy_num; i++) { pushElement(&stack, element); } program->lineNumber++; } else program->lineNumber++; } destroyStack(&stack); }
/** * Function: main() * Description: main routine of the shell. * Synopsis: int main(int argc, char* argv[]) (conforms to ANSI C) * Return value: * o An integer, indicating exit status. */ int main(int argc, char* argv[]) { char* prompts[] = { "msh", "rshell", "rsnoop" }; enum { P_MSH, P_RSHELL, P_RSNOOP }; int prompt = P_MSH; printf ( "\nWelcome to Microshell Client\nVersion: %s\nType '?' for help.\n", MICROSHELL_VERSION ); memset(&status, 0, sizeof(sh_status_t)); init(); /* We loop until we get the quit signal */ while(status.curr_signal != SH_QUIT) { char cmdline[CMD_LINE_MAX_CHARS] = {0}; /*sh_commands cmd_type;*/ /* Save our state here to restart from here * in case we got interrupted by a SIGALRM */ if(sigsetjmp(jmpbuf, SIGALRM)) { } /* Prompt */ printf("\n%s> ", prompts[prompt]); fgets(cmdline, CMD_LINE_MAX_CHARS, stdin); /* A copy of a command line for processing */ strcpy(status.cmdline, cmdline); if(status.curr_signal == SH_REMOTE) { if(prompt == P_RSHELL) rshell(cmdline); else rsnoop(cmdline); } else { /* Parse the command line */ status.curr_cmd = parseCmd(cmdline); prompt = P_MSH; /* Dispatch according to the command type */ switch(status.curr_cmd) { case QUIT: status.curr_signal = SH_QUIT; /*disconnect();*/ break; case SRV_RSHELL: /*rshell(cmdline);*/ connectSnoopSrv(cmdline); prompt = P_RSHELL; break; case SRV_RSNOOP: /*rsnoop(cmdline);*/ connectSnoopSrv(cmdline); prompt = P_RSNOOP; break; case REGISTER: /* Send connection request */ if(status.connected == true) fprintf(stderr, "This client already opened a connection to the server!\n"); else { connectTimeSrv(); initSignals(); } break; case SRV_VERSION: /* Send version request */ if(status.connected == false) fprintf(stderr, "Server Version Request: Not connected to the server yet.\n"); else srvVersion(); break; case SRV_ELAPSED_TIME: /* Send eslsapsed time request */ if(status.connected == false) fprintf(stderr, "Elapsed Time Request: Not connected to the server yet.\n"); else srvElapsedTime(); break; case SRV_TOD:/* Send time-of-the-day request */ if(status.connected == false) fprintf(stderr, "Time of the Day Request: Not connected to the server yet.\n"); else srvTOD(); break; case PIPELINE: execPipeline(status.pipeline_size, -1); reset(); break; case HELP: showHelp(); break; case BLANK: case UNKNOWN: /* UNKNOWN was meant for error checking. Unused. */ reset(); break; default: fprintf(stderr, "msh: Unexpected command type: %d (internal error)\n", status.curr_cmd); exit(1); } /* switch(status.curr_cmd) */ } /* !SH_REMOTE */ /* Make sure we don't have anything in those streams */ fflush(stdout); fflush(stdin); fflush(stderr); } /* while(not QUIT) */ exit(0); } /* main() */
int main ( int argc, char * argv[ ] ) { int nbytes; // Number of bytes int sock; // This will be our socket char buffer[ MAXBUFSIZE ]; // A buffer to buff things char cmd[ MAXBUFSIZE ]; // Command to be sent to Server char *newline = NULL; // Get newline Folder dir; // Local list of folder Files Repository repo; // Master file list // Make sure name, ip and port are given if ( argc < 4 ) { printf("USAGE: <client_name> <server_ip> <server_port>\n"); exit ( EXIT_FAILURE ); } sprintf( dir.name, "%s", argv[1] ); ls( &dir ); printf( "$ Welcome '%s'\n", dir.name ); sock = createSocket( inet_addr( argv[2] ), atoi( argv[3] ) ); connectPlease( &dir, sock ); // getMaster( &repo, sock ); // // Enter command loop // do { bzero( cmd, sizeof( cmd ) ); printf( "> " ); // // Grab Command Line // if ( fgets( cmd, MAXBUFSIZE, stdin ) != NULL ) { newline = strchr( cmd, '\n'); // Find the newline if ( newline != NULL ) *newline = '\0'; // Overwrite switch ( parseCmd ( cmd ) ) { case LS: printCatalog ( &dir ); break; case GET: getMaster( &repo, sock ); break; case EXIT: nbytes = write( sock, "EXIT", MAXBUFSIZE ); ERROR( nbytes < 0 ); break; default: nbytes = write( sock, cmd, MAXBUFSIZE ); ERROR( nbytes < 0 ); bzero( buffer, MAXBUFSIZE ); nbytes = read( sock, buffer, MAXBUFSIZE ); printf( "$ %s\n", buffer); break; } } } while ( !isQuit( cmd ) ); close( sock ); return EXIT_SUCCESS; } // main( )
void Tracker::enterDebuger(){ string cmd; //cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); while (true) { cout << "NoC"<<">"; vector<string> cmd = parseCmd(); if (cmd.size() == 0) continue; if (strcasecmp(cmd[0].c_str(), "quit")==0) break; else if (strcasecmp(cmd[0].c_str(), "help")==0) printDebugerHelp(0, cout); else if (strcasecmp(cmd[0].c_str(), "now")==0) cout << g_simCount << endl; else if (strcasecmp(cmd[0].c_str(), "dl") == 0){ char mode=0; string fileName=""; int ff = isfout(cmd, fileName, mode); if (ff == 1) { ofstream fout; if(mode == (char)ofstream::app) fout.open((gc_resultHome + fileName).c_str(), ofstream::app); else fout.open((gc_resultHome + fileName).c_str(), ofstream::out); if (!fout.is_open()) cout<<"Cannot open "<< (gc_resultHome + fileName) << "__" <<endl; else{ printDeadlock(fout); fout.close(); } } else if(ff == -1){ cout << "Miss output file name" << endl; // error, filename not input } else if (ff == 0) printDeadlock(cout); else; } else if (strcasecmp(cmd[0].c_str(), "rt") == 0){ bool noerr = true; if (cmd.size() == 3){ if (cmd[1].find_first_not_of("0123456789") == string::npos && cmd[2].find_first_not_of("0123456789") == string::npos){ int srcId = atoi(cmd[1].c_str()); int destId = atoi(cmd[2].c_str()); printRoutePath(srcId, destId, cout); } else noerr = false; } else noerr = false; if (!noerr) cout << "rt: rt srcId destId" << endl; } else if (strcasecmp(cmd[0].c_str(), "set")==0){ bool noerr = true; if (cmd.size() == 3){ if (strcasecmp(cmd[1].c_str(), "tile")==0) { if (cmd[2].find_first_not_of("0123456789") != string::npos) // not a integer noerr = false; else{ int tileId = atoi(cmd[2].c_str()); bool ret = enterDebugerTile(tileId); if (ret == false) break; // exit debugger } } else noerr = false; } else noerr = false; if (!noerr) cout << "set: set tile [tileId]" << endl; } else if (strcasecmp(cmd[0].c_str(), "view")==0) { bool noerr = true; if (cmd.size() >= 3) { vector<ULL> hier = parseHier(cmd[2]); if (hier.size() == 0){ cout << "Can't recognize location you input" << endl; noerr = false; } else{ if (hier[0] == 1) // rel path to abs path hier[0] = 0; char mode=0; string fileName=""; int ff = isfout(cmd, fileName, mode); if (ff == 1) { ofstream fout; if(mode == (char)ofstream::app) fout.open((gc_resultHome + fileName).c_str(), ofstream::app); else fout.open((gc_resultHome + fileName).c_str(), ofstream::out); if (!fout.is_open()) cout<<"Cannot open "<< (gc_resultHome + fileName) << "__" <<endl; else{ commandView(cmd[1], hier, fout); fout.close(); } } else if(ff == -1){ cout << "Miss output file name" << endl; // error, filename not input } else if (ff == 0) commandView(cmd[1], hier, cout); else; } } else cerr << "view: miss arguments" << endl; } else cout << "No such command" << endl; } }
void main(void) { unsigned char swTrig = 0; byte l3 = 1; lDelay(); Wait4NN = FALSE; isLearning = FALSE; led1timer = 0; doSOD = 0; ioIdx = 0; doEV = 0; evIdx = 0; NV1 = eeRead(EE_NV); initIO(); resetOutputs(); NN_temp = eeRead(EE_NN) * 256; NN_temp += eeRead(EE_NN + 1); if (NN_temp == 0 || NN_temp == 0xFFFF) NN_temp = DEFAULT_NN; CANID = eeRead(EE_CANID); if (CANID == 0 || CANID == 0xFF) CANID = NN_temp & 0xFF; initCAN(); delay(); restoreOutputStates(); delay(); SOD = eeRead(EE_SOD) * 256; SOD += eeRead(EE_SOD + 1); if (SOD == 0 || SOD == 0xFFFF) SOD = DEFAULT_SOD; // Loop forever (nothing lasts forever...) while (1) { CANMsg cmsg; unsigned char txed = 0; LED3 = PORT_ON; l3 ^= 1; // Check for Rx packet and setup pointer to it while (canbusRecv(&cmsg)) { // Decode the new command LED1 = 1; led1timer = 20; txed = parseCmd(&cmsg); } LED3 = PORT_OFF; doTimedOff(ioIdx); if (checkInput(ioIdx, doSOD)) { ioIdx++; if (ioIdx >= 16) { ioIdx = 0; doSOD = 0; } } if (l3) { if (doPortEvent(evIdx)) { evIdx++; if (evIdx >= 16) { evIdx = 0; doEV = 0; } } } if (checkFlimSwitch() && !swTrig) { swTrig = 1; } else if (!checkFlimSwitch() && swTrig) { swTrig = 0; if (Wait4NN) { Wait4NN = 0; LED2 = 0; } else { CANMsg canmsg; LED2 = 1; canmsg.b[d0] = OPC_RQNN; canmsg.b[d1] = NN_temp / 256; canmsg.b[d2] = NN_temp % 256; canmsg.b[dlc] = 3; canbusSend(&canmsg); Wait4NN = 1; } } } }
int main(void) { // Clock (50MHz) SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN); // Init peripherals // UART0/1 UART_Init(UART0); UART_Enable(UART0); UART_Init(UART1); UART_SetIRQ(UART1, UART_RX_IRQ, &UART1_RX_IRQ); UART_IntEnable(UART1, UART_RX_IRQ); UART_Enable(UART1); setbuf(stdout, NULL); u1BufPtr = u1Buf; // I2C0 I2C_Init(I2C0); I2C_Enable(I2C0); // PWM0/1 PWM_Init(PWM0, 50); PWM_Init(PWM1, 1000); PWM_Enable(rLED); PWM_Enable(gLED); PWM_Enable(bLED); PWM_Set(rLED, 0); PWM_Set(gLED, 0); PWM_Set(bLED, 0); // Init Robotics BoosterPack RoboticsBP_Init(); // NVIC IntMasterEnable(); // As soon as UART1 IRW is enabled, a character is // incorrectly received. Correct the issue by simply // resetting the buffer pointer. // Might be a bug in UART implementation of PAL u1BufPtr = u1Buf; // Start parsing commands as they become available cmdHead = u1Buf; cmdTail = u1Buf; while(1) { // Wait until buffPtr moves // Might be possible to use wfi() here if (cmdTail == u1BufPtr) continue; // This is apparently needed, otherwise everything doesn't work... printf("%c%d", *cmdTail, *cmdTail == ';'); // Increment pointer cmdTail++; // If command is complete if (*cmdTail == ';') { printf("\r\n"); // Fake the end of a string *cmdTail = 0; // Execute command parseCmd(); // Update pointers // Check if we need to loop back if (cmdTail > u1Buf + 1000) { // Reset pointers to beginning of buffer cmdHead = u1Buf; cmdTail = u1Buf; } else { // Upadte pointers cmdHead = ((unsigned char*) cmdTail) + 1; cmdTail = cmdHead; } } } }
//MAIN int main() { signal(SIGINT, sighandler); char cmd[MAX_COMMAND_LENGTH + 1]; char histar[10][MAX_COMMAND_LENGTH + 1]; char hischar[MAX_COMMAND_LENGTH + 1]; int a = 0; int piped =0; int redirin = 0; int redirout = 0; int hiscount = 0; while(1) { char* params[MAX_NUMBER_OF_PARAMS + 1]; printf("azarifog> "); // Read command from standard input if(fgets(cmd, sizeof(cmd), stdin) == NULL) break; // Remove trailing newline character, if any if(cmd[strlen(cmd)-1] == '\n') { cmd[strlen(cmd)-1] = '\0'; } //Copy the input for history to save later.. strncpy(hischar, cmd, MAX_COMMAND_LENGTH + 1); // Split cmd into array of parameters int n = parseCmd(cmd, params); // If exit is entered if(strcmp(params[0], "exit") == 0) break; //History if(strcmp(params[0], "history") == 0){ int count_num = 1; if(hiscount < 10) count_num = hiscount; else count_num = 10; for(int h = 0 ; h < count_num; h++){ printf("%s\n" , histar[h]); } continue; } else { int hc = hiscount % 10; strcpy(histar[hc], hischar); //printf("Copying to index at %d: %s\n" ,hc, hischar); hiscount++; } //Check variables to find out if commands is pipe or redirect for(a = 0; a < n; a++){ if(!strcmp(params[a], "|")){ piped++; //pipe command entered //printf("piped: %i", piped); } if(!strcmp(params[a], "<")){ redirin++; //redireted in command //printf("redirin: %i", redirin); } if(!strcmp(params[a], ">")){ redirout++; //redirected out command //printf("redirout: %i", redirout); } } //If there is no need for pipe or redirection if(piped == 0 && redirin == 0 && redirout == 0){ //printf("PARAM: %s\n", params[0]); if(executeCmd(params) == 0) break; } else{ //If there is a need for pipe if(piped != 0 ){ //Pipe function do_pipe(params, piped); } //If there is redirection else if(redirin == 1 || redirout == 1){ int ic1 = 2; int ic2 = 4; for(int i=0;params[i]!='\0';i++) { if(strcmp(params[i],"<")==0) { params[i]=NULL; ic1 = i+1; } else if(strcmp(params[i],">")==0) { params[i]=NULL; ic2 = i+1; } } // Fork process pid_t pid = fork(); // Error if (pid == -1) { char* error = strerror(errno); printf("fork: %s\n", error); return 1; } // Child process else if (pid == 0) { int in, out; int p = 0; char *args2[MAX_COMMAND_LENGTH + 1] = {}; for(p =0; p < ic1; p++){ args2[p] = params [p]; //printf("%s" , args2[p]); } args2[p] = NULL; // Open input and output files if(redirin == 1){ in = open(params[ic1], O_RDONLY); //Error handling if the file does not exist. if(in == -1){ printf("The file does not exist: %s\n", params[ic1]); piped = 0; redirin = 0; redirout = 0; close(in); break; } // Replace standard input with input file dup2(in, 0); close(in); } if(redirout == 1){ out = open(params[ic2], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); // replace standard output with output file dup2(out, 1); close(out); } // execute arguments execvp(args2[0], args2); // Error occurred char* error = strerror(errno); printf("Error! azarifog: %s: %s\n", params[0], error); } // Parent process else { // Wait for child process to finish int childStatus; waitpid(pid, &childStatus, 0); } } // redirect } //reset variables piped = 0; redirin = 0; redirout = 0; //For the signal handler testing //sleep(1); } return 0; }