首页 > 编程语言 > 详细

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

时间:2020-01-20 23:56:15      阅读:251      评论:0      收藏:0      [点我收藏+]

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;
    }
}

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

原文:https://www.cnblogs.com/justsong/p/12219782.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!