【Linux】简单的shell模拟实现(代码)

本文介绍了一个使用C++实现的简易Shell命令解析器,支持基本的ls、-a、-l、top等命令,通过fork和execvp系统调用执行命令,并展示了如何处理命令输入和输出状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

支持简单的ls、-a、-l、top等命令,|(管道)、>(重定向)等不支持
shell.c代码

 #include <iostream>
 #include <string>
 #include <cstdio>
 #include <cstring>
 #include <unistd.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <sys/wait.h>
  
 #define NUM 32
 using namespace std;
 
 int main()
 {
      char buff[1024] = {0};
      for(;;)
     {
 
          string command;
          string tips = "[XXX@localhost YYY]# ";
          cout << tips;
          fgets(buff,sizeof(buff)-1,stdin);
          buff[strlen(buff)-1] = 0;
         // cout << buff << endl;
           char *argv[NUM];
          argv[0] = strtok(buff," ");
          int i = 0;
          while(argv[i]!=NULL)
          {
                i++;
               argv[i] = strtok(NULL," ");
          }
          pid_t id = fork();
          if(id == 0)
           {
               cout << "child running..." << endl;
               execvp(argv[0],argv);
               exit(123);
           }
           else
           {
               int status = 0;
               waitpid(id,&status,0);
               cout << "Exit Code:" << WEXITSTATUS(status) << endl;
           }
  
     }
   return 0;
   }

结果截图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值