做一个简易的shell

shell建立一个新进程,然后在那个进程中运行ls程序并等待那个进程结束

循环以下过程:

1.获取命令行

2.解析命令行

3.建立一个子进程(fork)

4.替换子进程(execvp)

5.父进程等待子进程退出

代码如下:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<wait.h>   
int main()
{
   int i=0;
   char *myargv[NUM];
   char cmd[MAX];
   while(1)
   {   
                   printf("[bit@localhost myshell]#");
                   fgets(cmd,sizeof(cmd),stdin);
                   cmd[strlen(cmd)-1]='\0';
                   myargv[i++]=strtok(cmd," ");
                   char *ret=NULL;
                   while(ret=strtok(NULL," ")){
                                    myargv[i++]=ret;
                   }   
                   myargv[i]=NULL;
                   pid_t id=fork();
                   if(id==0)
                   {   
                                   execvp(myargv[0],myargv);
                                   exit(1);
                   }   
                   else
                   {   
                              waitpid(id,NULL,0);
                   }   
   }   
   int j=0;
   for(j=0;j<i;j++)
   {   
            printf("%s\n",myargv[j]);
   }   
   return 0;     
}           

 

以下是一个简易shell程序,可以在Linux下用C语言编写: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #define MAX_LINE 80 /* 命令行最大长度 */ int main(void) { char *args[MAX_LINE / 2 + 1]; /* 命令行参数 */ char input[MAX_LINE + 1]; /* 命令行输入 */ int should_run = 1; /* 判断是否退出shell */ pid_t pid; /* 进程ID */ while (should_run) { printf("osh> "); fflush(stdout); /* 刷新输出缓冲区 */ fgets(input, MAX_LINE, stdin); /* 读取命令行输入 */ /* 将输入字符串拆分为参数数组 */ char *token; int i = 0; token = strtok(input, " \n"); while (token != NULL) { args[i++] = token; token = strtok(NULL, " \n"); } args[i] = NULL; /* 参数数组以NULL结尾 */ /* 检查是否退出shell */ if (strcmp(args[0], "exit") == 0) { should_run = 0; continue; } /* 创建子进程执行命令 */ pid = fork(); if (pid < 0) /* 创建进程失败 */ { fprintf(stderr, "fork failed\n"); return 1; } else if (pid == 0) /* 子进程 */ { execvp(args[0], args); /* 执行命令 */ fprintf(stderr, "execvp failed\n"); /* 如果execvp返回,则表示执行失败 */ return 1; } else /* 父进程 */ { wait(NULL); /* 等待子进程结束 */ } } return 0; } ``` 该程序的基本思路是每次读取一行命令行输入,将输入字符串拆分为参数数组,然后创建一个子进程执行命令,等待子进程结束后再读取下一行输入。如果输入的第一个参数是“exit”,则退出程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值