在shell中输入“ls || more"能够执行ls命令并将其通过管道传送给more作为标准输入。
源码
#include<stdio.h>
#include<unistd.h>
#include<wait.h>
#include<string.h>
int main(){
printf("welcome to my shell!\n");
char cmd[1024];
//printf("%d\n",argc);
while(1){
printf("myshell> ");
gets(cmd);
if(strcmp(cmd, "exit")==0) break;
else if(strcmp(cmd, "help")==0){
printf("-----------\ninner commands: \n");
printf("help: print help infomation\n");
printf("story: tell stories\n");
printf("exit: exit this\n -----------\nouter commands:\n");
printf("command:ps-ls--\n-----------\n");
printf("command-pipe: ||\n:");
}
else if(strcmp(cmd, "story")==0){
printf("no stories to tell you!\n");
}
else if(strstr("ls-ps",cmd)!=NULL){
/*char *argv[10];
char *p;
int argc = 1;
char delims[2]=" ";
strcpy(argv[0], strtok(cmd, delims));
while(p = strtok(NULL, delims)){
strcpy(argv[argc],p);
argc++;
}*/
//printf("argc:%d\n",argv[0]);
pid_t pid = fork();
if(pid > 0) // parent
{
wait(NULL);
continue;
}
if(pid==0) //child
{
int s = execlp(cmd, cmd, NULL);
if(s==-1) printf("fail to exec %s\n", cmd);
return 0;
}
}
else if(strstr(cmd,"||")!=NULL){
puts(cmd);
const char s[3] = "| ";
char *command1;
char *command2;
int fd[2], res;
int status;
command1 = strtok(cmd, s);
command2 = strtok(NULL, s);
printf("%s\n", command1);
printf("%s\n", command2);
res = pipe(fd);
if(res == -1){
printf("pipe failed!\n");
}
pid_t pid1 = fork();
if(pid1 == -1){
printf("fork failed !\n");
}
else if(pid1 == 0){
int num1 = dup2(fd[1], 1); // dup the stdout
close(fd[0]);
if(execlp(command1,command1, NULL)<0){
printf("%s: command not found\n", command1);
}
}
else{
waitpid(pid1, &status, 0);
pid_t pid2 = fork();
if(pid2 == -1)
printf("fork failed!\n");
else if(pid2 == 0){
close(fd[1]); //close write edge
dup2(fd[0], 0);
if(execlp(command2,command2, NULL)<0){
printf("%s:command not found\n",command2);
}
}
else{
close(fd[0]);
close(fd[1]);
waitpid(pid2, &status, 0);
}
}
}
else {
printf("invalid command!\n");
}
}
return 0;
}
113,1 Bot
只实现了简单的功能,更加丰富的功能可以扩展。