Linux 06-01:简易shell编写
创始人
2024-12-26 20:35:02
0

        考虑一下这个与shell典型的互动:ls、ps

        用下图的时间轴来表示事件的发生次序。其中时间从左向右。shell由标识为sh的方块代表,它随着时间的流逝从左向右移动。shell从用户读入字符串"ls"。shell建立一个新的进程,然后在那个进程中运行ls程序并等待那个进程结束。

        然后shell读取新的一行输入,建立一个新的进程,在这个进程中运行程序 并等待这个进程结束。
        所以要写一个shell,需要循环以下过程:

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

        根据这些思路,和我们前面的学的技术,就可以自己来实现一个shell了。

示例代码:

#include  #include  #include  #include  #include  #include  #include   #define MAXSTRLEN 1024 #define NUM 64 void GetCommand(char *command, int size) {     char *r = fgets(command, size - 1, stdin);     if (r == NULL)     {         return;     }     command[strlen(command) - 1] = '\0'; }  void AnalyseCommand(char *command, char *argv[]) {     int n = 0;     argv[n++] = strtok(command, " ");     while (argv[n++] = strtok(NULL, " "))         ; } void run(char *argv[]) {     int pid = fork();     if (pid < 0)     {         perror("fork");     }     else if (pid == 0) // 子进程     {         execvp(argv[0], argv);         exit(1);     }     else     { // 父进程             } } int main() {      while (1)     {         char command[MAXSTRLEN];         printf("[%s]", getenv("PWD"));         // 获取指令         GetCommand(command, sizeof(command));         // 解析指令         char *argv[NUM];         AnalyseCommand(command, argv);          // 运行指令         run(argv);     } }

这是一个极其简易的示例代码,没有任何的差错控制,健壮性极弱,仅为示范

相关内容

热门资讯

wepower有外挂!hhpo... wepower有外挂!hhpoker德州有挂(透视)存在挂教程(有挂猫腻)-哔哩哔哩;1、超多福利:...
wepokeai机器人!wej... wepokeai机器人!wejoker透视方法(透视)细节揭秘(确实有挂)-哔哩哔哩;亲真的是有正版...
wepokeai代打的胜率!p... wepokeai代打的胜率!pokermaster脚本(透视)黑科技教程(有挂秘笈)-哔哩哔哩是一款...
wepoke黑科技!德普之星透... wepoke黑科技!德普之星透视辅助软件是真的(透视)教你攻略(有挂方略)-哔哩哔哩是一款可以让一直...
wepoke是真的有挂!hh ... wepoke是真的有挂!hh poker辅助有用(透视)细节方法(有挂功能)-哔哩哔哩;最新版202...
wepokeai代打逻辑!po... wepokeai代打逻辑!pokemmo手机版脚本免费(透视)透明教程(真的有挂)-哔哩哔哩;是一款...
wepoke有app软件!we... wepoke有app软件!wepoker辅助工具(透视)透牌教程(有挂分析)-哔哩哔哩;wepoke...
wepok软件透明挂!哈糖大菠... 【福星临门,好运相随】;wepok软件透明挂!哈糖大菠萝软件下载(透视)2025新版教程(揭秘有挂)...
七分钟了解!新畅游互娱科技(辅... 七分钟了解!新畅游互娱科技(辅助挂)详细透视开挂辅助新2025版(切实真的有挂)-哔哩哔哩;1、首先...
wepokeai代打逻辑!德州... wepokeai代打逻辑!德州hhpoker脚本(透视)辅助教程(有挂秘笈)-哔哩哔哩;是一款可以让...