实现一个简单的 Linux Shell(C++)

Implement a simple command interpreter in Linux. The interpreter should:

  1. support both internal and external commands, and internal commands support two (cd, exit);
  2. able to save 10 historical commands

The following system calls can be used to implement the interpreter:

  1. fork() —create a new process;
  2. execve() —Load a new program and execute it;
  3. wait() —waiting for child process to exist
  4. chdir() —change the working direction of a process.

完整代码实现:

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define TRUE 1
#define MAX_SIZE 1024

void print_prompt(){
    char cwd[MAX_SIZE];
    if (getcwd(cwd, sizeof(cwd)) != NULL) {
        printf("🐴 @💻 :\033[0;34m%s\033[0m💲 ", cwd);
    }
}

int read_input(char* str){
    char buf[MAX_SIZE]; 
    fgets(buf, MAX_SIZE, stdin); 
    if (strlen(buf) != 1) { 
        strcpy(str, buf); 
        return 1; 
    } else {
        return 0; 
    }
}

int exec_command(char* user_input){
    char* inputs[MAX_SIZE];
    bzero(inputs, MAX_SIZE); // Very imortant, fuck gcc!
    char* token = strtok(user_input, " ");
    int i=0;
    while (token != NULL) {
        inputs[i] = token;
        i++;
        token = strtok(NULL, " "); 
    }
    if(strcmp(inputs[0], "exit")==0){
        printf("Bye.\n");
        return 1;
    }
    if(strcmp(inputs[0], "cd")==0){
        chdir(inputs[1]);
        return 0;
    }
    char path[100];
    bzero(path, 100);
    strcat(path, "/bin/");
    strcat(path, inputs[0]);
    if (fork() != 0){
        int *status;
        waitpid(-1, status, 0);
    } else {
        execve(path, inputs, 0);
    }
    return 0;
}

void main(){
    while(TRUE){
        char input_string[MAX_SIZE];
        print_prompt();
        if(!read_input(input_string)) continue;
        int len = strlen(input_string);
        input_string[len-1]='\0';
        if(exec_command(input_string)) break;
    }
}
posted @ 2020-01-20 23:12  JustSong  阅读(1286)  评论(0编辑  收藏  举报