Linux 用exce族函数实现minishell

1.函数功能:

实现Linux下的基本命令,平替系统的minishell。在这里需要注意,ll 和cd  因为cd属于外部命令,意思是在系统下cd 的命令的路径不在linux下,(在/bin/下)。而ll 是“ls -alhF”的别称,在linux下也不能识别,所以要将 ll换成  ls -alhF 。



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/wait.h>
void show_prort()
{
    char path[512]={0};
    getcwd(path,sizeof(path));
    printf("linux@ubuntu:%s$",path);
    fflush(stdout);
}

int main(int argc, char *argv[])
{
    int flag = 1;
    while(flag)
    {
        show_prort();
        char cmd[512]={0};
        //fgets(cmd,sizeof(cmd),stdin);
        read(0,cmd,sizeof(cmd));
        cmd[strlen(cmd)-1]='\0';
        if(strlen(cmd)==0) //cmd ==NULL
        {
           continue;
        }
        char *arg[10]={NULL};
        arg[0]=strtok(cmd," ");
        arg[1]=strtok(NULL," ");
        arg[2]=strtok(NULL," ");
        arg[3]=strtok(NULL," ");
        arg[4]=strtok(NULL," ");

        if(0 == strcmp(arg[0],"cd"))
        {
        
            if(NULL == arg[1])
            {
                chdir("/home/linux");
            }
            else 
            {
                chdir(arg[1]);
            }
        
            continue;
        }
        if(0 == strcmp(arg[0],"quit"))
        {
            flag = 0 ;
            continue;
        }

        pid_t pid = fork();
        if(pid>0)
        {
            wait(NULL);
        }
        else if (0 == pid)
        {
            if(0==strcmp(arg[0],"ll")) // ll   ll /home
            {
                if(NULL == arg[1])
                {
                    arg[0]="ls";
                    arg[1]="-alhF";
                }
                else 
                {
                    arg[0]="ls";
                    arg[2]="-alhF";
                }
            }
            execvp(arg[0],arg);
            exit(1);
        }
        else 
        {
            perror("fork");
            exit(1);
        }
    }
    return 0;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值