shell.c 2.2 KB
Newer Older
H
2-15  
hypo 已提交
1 2 3 4 5 6
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

H
unit 2  
hypox64 已提交
7 8 9
#define SH_TOK_BUFSIZE 64
#define SH_TOK_DELIM " \t\r\n\a"

H
2-15  
hypo 已提交
10 11 12 13
char *shell_read_line();
char **shell_split_line(char * line);
int shell_execute(char **args);

H
unit 2  
hypox64 已提交
14 15


H
2-15  
hypo 已提交
16 17 18
void shell_loop(void){
	char *line;
	char **args;
H
unit 2  
hypox64 已提交
19 20 21

	int size;
	while(1){
H
2-15  
hypo 已提交
22 23 24
		printf(">>");
		line = shell_read_line();
		args = shell_split_line(line);
H
unit 2  
hypox64 已提交
25
		shell_execute(args);
H
2-15  
hypo 已提交
26 27
		free(line);
		free(args);
H
unit 2  
hypox64 已提交
28 29 30

	}

H
2-15  
hypo 已提交
31 32 33 34 35 36 37 38 39
}

char *shell_read_line(){
	char *line = NULL;
	ssize_t bufsize = 0; // getline()function will help us allocate a buffer
	getline(&line,&bufsize,stdin);
	return line;
}

H
unit 2  
hypox64 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
char **shell_split_line(char *line){
	int bufsize = SH_TOK_BUFSIZE;
	int position = 0;
	char **tokens = malloc(bufsize * sizeof(char*));
	char **token;

	if(!tokens){
		fprintf(stderr,"allocation error!\n");
		exit(EXIT_FAILURE);
	}

	token = strtok(line,SH_TOK_DELIM);

	while(token != NULL){
		tokens[position] = token;
		position++;

		if(position >= bufsize){
			bufsize += SH_TOK_BUFSIZE;
			tokens = realloc(tokens,bufsize * sizeof(char*));
			if(!tokens){
				fprintf(stderr,"allocation error!\n");
				exit(EXIT_FAILURE);
			}
		}
		token = strtok(NULL,SH_TOK_DELIM);
	}
	tokens[position] = NULL;
	return tokens;
}

// char *shell_read_line(){
// 	static char buff[1024];
//   	//scanf("%s", buff);
// 	fgets(buff, sizeof(buff), stdin);
// 	// printf("stren buff[%ld]\n", strlen(buff));
// 	buff[strlen(buff)-1] = '\0';
// 	return buff;

// }

int shell(char **args){
	pid_t pid,wpid;
	int status;
	pid = fork();
    if(pid == -1 ) 
    {
        printf("error!\n");
    } 
    else if( pid ==0 ) 
    {
    	if(execvp(args[0],args) == -1){
			perror("shell");
		}
		exit(EXIT_FAILURE);
    	// execvp(args[0],args);

    }
	do {
		wpid = waitpid(pid,&status,WUNTRACED);
	}while (!WIFEXITED(status) && !WIFSIGNALED(status));
	return 1;

}


int shell_execute(char **args)
{
	// printf("%s\n",args[0] );

	if (strcmp(args[0], "help") == 0){
		printf("%s\n","This is a smaple shell build by C @Hypo");
	}
	else if(strcmp(args[0], "exit") == 0){
		exit(0);
	}
	else if(strcmp(args[0], "cd") == 0){
		printf("%s\n","No such command!" );
	}
	else{
		shell(args);
	}
}

H
2-15  
hypo 已提交
124 125 126 127
int main(int argc, char **argv[])
{
	shell_loop();
}