Linux进程控制+基础IO-minishell增加重定向

该代码段展示了一个用C语言编写的简易Shell程序,它能接收用户输入的命令并执行。程序支持文件重定向,包括清除和追加两种模式。通过fork和execvp系统调用在子进程中执行命令,实现了基本的命令解析和执行功能。
摘要由CSDN通过智能技术生成

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<fcntl.h>
#include<sys/wait.h>

int main(int argc,char* argv[])
{
  while(1)
  {
    char buf[1024]={0};
    printf("[user@host path]$ ");
    fflush(stdout);//刷新缓冲区 printf是行缓冲,不刷新不打印
    fgets(buf,1023,stdin);
    buf[strlen(buf)-1]='\0';
   // printf("buf:[%s]\n",buf);

    char* str=buf;
    int redirect_flag=0;//1-清空 2-追加
    char* redirect_file=NULL;
    printf("str=%s\n",str);
    while(*str!='\0')
    {
      if(*str=='>')
      {
         //printf(">\n");
        redirect_flag=1;
        *str='\0';
        str++;
        if(*str=='>')
        {
          redirect_flag=2;
          *str='\0';
          str++;
        }
      
      while(*str!='\0'&&*str==' ')
      {
        str++;
      }

      redirect_file=str;

      while(*str!='\0'&&*str!=' ')
      {
          str++;
      }
      *str='\0';
    }
      str++;
  }

    printf("%d-%s-%s\n",redirect_flag,redirect_file,buf);
    fflush(stdout);
    char* ptr=buf;
    char myargv[32][32]={0};
    int myargc=0;
    while(*ptr!='\0')
    {
      if(!isspace(*ptr))
      {
        int count=0;
        while(*ptr!='\0' && !isspace(*ptr))
        {
          myargv[myargc][count]=*ptr;
          count++;
          ptr++;
        }
        myargc++;
      }
      ptr++;
    }
    //for(int i=0;i<myargc;i++)
    // {
    //  printf("myargv[%d]=[%s]\n",i,myargv[i]);
    // }
    if(strcmp(myargv[0],"cd")==0)//实现CD命令
    {
      chdir(myargv[1]);
      continue;
    }
    char* arg[32]={NULL};
    int i;
    for(i=0;i<myargc;i++)
    {
      printf("[%s]",myargv[i]);
      arg[i]=myargv[i];
    }
    fflush(stdout);
    arg[myargc]=NULL;
    pid_t pid = fork();
    if(pid<0)
    {
      printf("创建失败");
      continue;
    }
    else if(pid==0)
    {
      printf("子进程");
      if(redirect_flag==1)
      {
        printf("flag=1");
        int fd = open(redirect_file,O_CREAT|O_TRUNC|O_WRONLY,0664);
        dup2(fd,1);
      }
      else if(redirect_flag==2)
      {
        printf("flag=2");
        int fd = open(redirect_file,O_CREAT|O_APPEND|O_WRONLY,0664);
        dup2(fd,1);
      }
      execvp(arg[0],arg);
      exit(-1);
    }
    wait(NULL);
  }
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值