编程实现linux下的shell
/************************************************************************* > File Name: Kris_shell.c > Author: KrisChou > Mail:[email protected] > Created Time: Thu 21 Aug 2014 04:31:55 PM CST ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <sys/wait.h> #define PROMPT ">>" #define ARG_CNT 32 void command_to_arglist(char** arglist,char *cmd_line);
int main(int argc, char *argv[]) { char cmd_line[1024]; char *arglist[ARG_CNT]; while(memset(cmd_line,0,1024), printf("%s",PROMPT), fgets(cmd_line,1024,stdin)) { if(cmd_line[0] != ‘\n‘) { cmd_line[strlen(cmd_line) - 1] = ‘\0‘; //将读进来的换行符变成‘\0‘ command_to_arglist(arglist,cmd_line); if(fork() > 0) { wait(NULL); }else { execvp(arglist[0],arglist); exit(0); } } } return 0; } static int my_isspace(char c) { if(c == ‘ ‘|| c == ‘\n‘ || c == ‘\t‘ || c ==‘\v‘) return 1; else return 0; }
static void command_to_arglist(char** arglist,char *cmd_line) { int cnt = 0; int bg,end; bg = 0; while(cmd_line[bg] != ‘\0‘) { while(my_isspace(cmd_line[bg])) { bg++; } if(cmd_line[bg] == ‘\0‘) { break; } end = bg; while(cmd_line[end] != ‘\0‘ && !my_isspace(cmd_line[end])) { end++; } arglist[cnt] = (char*)calloc(1, (end-bg+1)); strncpy(arglist[cnt],cmd_line+bg,(end-bg)); cnt++; bg = end; } arglist[cnt] = NULL; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。