#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;
}
Linux进程控制+基础IO-minishell增加重定向
于 2023-03-03 19:35:30 首次发布
该代码段展示了一个用C语言编写的简易Shell程序,它能接收用户输入的命令并执行。程序支持文件重定向,包括清除和追加两种模式。通过fork和execvp系统调用在子进程中执行命令,实现了基本的命令解析和执行功能。
摘要由CSDN通过智能技术生成