📄 shell.c
字号:
#include <stdio.h>#include <stdlib.h>#include <sys/stat.h>#include <sys/types.h>#include <fcntl.h>#include <unistd.h>#include <sys/wait.h>#include <string.h>#include "blank.h"int main(int argc,char *argv[]){ pid_t pid,PID; int fd; int fp[2]; int flag=0; char com[100]="\0"; char *name[20]; char *ps_argv[20]; char file[20]; int i=0,t=0,k=0; char *p,*q,*r,*f1,*f2; int stat_c=0; while(1) { pid=fork(); if(pid<0) { printf("fork error !\n"); return 1; } if(pid==0) { while(strcmp(com,"exit")!=0) { printf("[myshell@rain]# "); gets(com); if(strcmp(com,"exit")==0) exit(4); blank(com); r=p=q=com; if(*r==' ') r=r+1; if(*r=='\0') exit(1); i=0; p=strchr(r,' '); while(p!=NULL) { if(*(p+1)=='\0') { *p='\0'; break; } if(*(p+1)=='>') { if(*(p+2)=='>') { flag=2; f1=p+4; } else { flag=1; f1=p+3; } *p='\0'; f2=strchr(f1,' '); f2='\0'; strcpy(file,f1); break; } if(*(p+1)=='|') { *p='\0'; t=i+1; flag=3; } name[i]=(char *)malloc(20); q=p+1; *p='\0'; strcpy(name[i],r); r=q; i++; p=strchr(r,' '); } name[i]=(char *)malloc(20); strcpy(name[i],r); i++; name[i]=(char *)malloc(20); name[i]=NULL; if(flag==1||flag==2) { if(flag==1) fd=open(file,O_WRONLY|O_CREAT,0600); if(flag==2) fd=open(file,O_WRONLY|O_CREAT|O_APPEND,0600); dup2(fd,STDOUT_FILENO); } if(flag==3) { name[t]=NULL; t=t+1; while(name[t]!=NULL) { ps_argv[k]=(char *)malloc(20); strcpy(ps_argv[k],name[t]); printf("name[%d]=%s,ps[%d]=%s\n",t,name[t],k,ps_argv[k]); k++; t++; } ps_argv[k]=NULL; if(pipe(fp)<0) exit(1); if(PID=fork()<0) exit(1); if(PID==0) { close(fp[0]); dup2(fp[1],STDOUT_FILENO); execvp(name[0],name); } else { close(fp[1]); dup2(fp[0],STDIN_FILENO); // execvp(ps_argv[0],ps_argv); } } stat_c=execvp(name[0],name); if(stat_c==-1) printf("-myshell:%s:command not found\n",com); } } else { int stat_val; wait(&stat_val); if(flag>0) close(fd); if(WIFEXITED(stat_val)) { if(WEXITSTATUS(stat_val)==4) exit(0); } } } return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -