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

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

相关推荐
bantinghy20 分钟前
Linux系统TCP/IP网络参数优化
linux·网络·tcp/ip
星期天要睡觉25 分钟前
Linux 综合练习
linux·运维·服务器
梁辰兴1 小时前
数据结构:排序
数据结构·算法·排序算法·c·插入排序·排序·交换排序
saynaihe1 小时前
proxmox8升级到proxmox9
linux·运维·服务器
Delphi菜鸟1 小时前
docker 部署RustDesk服务
运维·docker·容器
野犬寒鸦1 小时前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试
Orchestrator_me1 小时前
CentOS交换区处理
linux·运维·centos
zru_96021 小时前
centos 系统如何安装open jdk 8
java·linux·centos
FLS1681 小时前
VMwaer虚拟机安装完Centos后无法联网问题
linux·运维·centos
菜鸟得菜1 小时前
leecode kadane算法 解决数组中子数组的最大和,以及环形数组连续子数组的最大和问题
数据结构·算法·leetcode