实现一个简单的 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;
    }
}

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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/192103

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午5:56
下一篇 2023年2月12日 下午5:56

相关推荐