Linux编写简易shell

思路:​


所以要写一个shell,需要循环以下过程:​

  1. 获取命令行
  2. 解析命令行
  3. 建立一个子进程(fork)
  4. 替换子进程(execvp)
  5. 父进程等待子进程退出(wait)

实现代码:​

复制代码
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <string.h>
 #include <fcntl.h>
 #define MAX_CMD 1024
 char command[MAX_CMD];
 int do_face()
 {
    memset(command, 0x00, MAX_CMD);
    printf("minishell$ ");
    fflush(stdout);
    if (scanf("%[^\n]%*c", command) == 0) {
        getchar();
        return -1; 
    }   
    return 0;
 }
 char **do_parse(char *buff)
 {
    int argc = 0;
    static char *argv[32];
    char *ptr = buff;
    while(*ptr != '\0') {
        if (!isspace(*ptr)) {
            argv[argc++] = ptr;
            while((!isspace(*ptr)) && (*ptr) != '\0') {
                ptr++;
            }
        }else {
            while(isspace(*ptr)) {
                *ptr = '\0';
                ptr++;
            }
        }
    }
    argv[argc] = NULL;
    return argv;
 }
 int do_exec(char *buff)
 {
    char **argv = {NULL};
	int pid = fork();
	if (pid == 0) {
        argv = do_parse(buff);
        if (argv[0] == NULL) {
            exit(-1);
        }
        execvp(argv[0], argv);
    }else {
        waitpid(pid, NULL, 0);
    }
    return 0;
 }
 int main(int argc, char *argv[])
 {
    while(1) {
        if (do_face() < 0)
            continue;
        do_exec(command);
    }
    return 0;
 }

以上就是本文的全部内容,如果对你有帮助,欢迎点赞收藏转发评论!

相关推荐
思麟呀3 小时前
Linux的基础IO流
linux·运维·服务器·开发语言·c++
星释3 小时前
Rust 练习册 :Pythagorean Triplet与数学算法
开发语言·算法·rust
星释3 小时前
Rust 练习册 :Nth Prime与素数算法
开发语言·算法·rust
winner88813 小时前
嵌入式Linux驱动开发全流程:工具协作+核心概念拆解(从入门到理解)
linux·运维·驱动开发
ShiinaKaze3 小时前
fatal error: bits/c++config.h: No such file or directory
linux·gcc·g++
多喝开水少熬夜4 小时前
Trie树相关算法题java实现
java·开发语言·算法
TTBIGDATA4 小时前
【Ambari开启Kerberos】KERBEROS SERVICE CHECK 报错
大数据·运维·hadoop·ambari·cdh·bigtop·ttbigdata
Archy_Wang_14 小时前
脚本自动生成专业Linux巡检报告
linux·运维·服务器
WBluuue4 小时前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
bruk_spp4 小时前
牛客网华为在线编程题
算法