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

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

相关推荐
知白守黑2673 小时前
docker资源限制
运维·docker·容器
霍格沃兹测试开发学社测试人社区3 小时前
新手指南:通过 Playwright MCP Server 为 AI Agent 实现浏览器自动化能力
运维·人工智能·自动化
ximy13354 小时前
AI服务器工作之服务器的种类分类
运维·服务器
恒创科技HK4 小时前
香港服务器CPU中E5和Gold的区别
运维·服务器
Han.miracle4 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
一张假钞6 小时前
Ubuntu SSH 免密码登陆
linux·ubuntu·ssh
mit6.8246 小时前
前后缀分解
算法
Wang's Blog7 小时前
Linux小课堂: 文件操作警惕高危删除命令与深入文件链接机制
linux·运维·服务器
你好,我叫C小白7 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
水月wwww8 小时前
操作系统——进程管理
linux·操作系统·vim·进程·进程调度