2012-11-12 91 views
1
#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <string.h> 
#include <sys/stat.h> 
#include <fcntl.h> 

void exec(char **args){ 
    pid_t pid; 
    int status; 
    if ((pid = fork()) < 0) {  
    printf("*** ERROR: forking child process failed\n"); 
    exit(1); 
} 

else if (pid == 0) {  

    if(execvp(args[0],args)<0)//{ 
     //printf("argv[0]=%s argv[1]=%s",args[0],args[1]); 
     printf("**error in exec\n"); 
    } 

    else {         
     while (wait(&status) != pid); 
    } 
} 

void exec2(char **args, char *file){ 
    printf("file =%s\n",file); 
    int fd; 
    pid_t pid; 
    int status; 
    if ((pid = fork()) < 0) {  
printf("*** ERROR: forking child process failed\n"); 
     exit(1); 
    } 

    else if (pid == 0) { 
    fd = open(file, O_RDWR | O_CREAT, (mode_t)0600); 
    close(1); 
    dup2(fd, 1); 
    if(execvp(args[0],args)<0){ 
     printf("**error in exec"); 
    } 

else { 
     printf("\nhere\n"); 
     close(fd);         
     while (wait(&status) != pid){ 
      fflush(stdout) ; 
     } 
    } 
} 
    close (fd); 
} 


void main(){ 
    char *command; 
    char inp[512]; 
    char *filepath; 
    size_t size=0; 
    char *substr; 
    char *args[512]; 
    command = (char *) malloc(sizeof(char *) * 512); 
    int flag=0; 
    int redirect=0; 
    int i=0; 
    while (1){ 
     printf("$ "); 
     command = fgets(inp, 512/*sizeof(char *)*/, stdin); 

     command[strlen(command)-1]='\0'; 

     if (strchr(command,'>')){ 
      redirect=1; 
      strtok_r(command,">",&filepath); 
     } 

     size_t siz=4; 
     //printf("command=%s\n",command); 
     int i=0; 
     while(1){ 
      //printf("i=%d\n",i); 
      char *tok = strtok_r(command," ",&substr); 
      if (tok==NULL){ 
       break; 
      } 
     args[i++] = tok; 
/*   printf("tok=%s\n",tok); 
      printf("len tok = %d\n",(int)strlen(tok)); 
      printf("command=%s\n",command); 
      printf("substr=%s\n",substr);  
    */   command = substr; 
     } 

     //printf("args[0]=%s",args[0]); 
     if (!strncasecmp(args[0],"exit",siz) || !strncasecmp(args[0],"quit",siz)) 
     { 
      printf("\nBye\n"); 
      exit(0); 
     } 

     else if(strcmp(args[0],"cd")==0){ 
      chdir(args[1]); 
      //printf("chdir") ; 
      //system("pwd"); 
    } 

    else if (redirect==1){ 
     exec2(args,filepath); 
    } 

    else exec(args); 
} 
} 

好吧,這是我爲我的shell代碼。當我運行它,我把ls,它給出正確的輸出。然後,我把ls -l命令,然後再LS和它給 LS:無法訪問:沒有這樣的文件或目錄 還當我使用CD,LS犯規給輸出和pwd說:「忽略未使用的參數」 也是貓不工作。 雖然mkdir,ps和ls -l起作用。製作外殼功課

+0

你的牙套和您的壓痕不匹配。你應該檢查你關閉你的牙套的地方。 – kmkaplan

回答

3

不要關閉stdout

像這樣做,在fork之後和之前exec

if (child) { 
    int fd = open(file, O_RDWR | O_CREAT, (mode_t)0600); 
    close(1); 
    dup2(fd, 1); 
    if(execvp(args[0],args)<0){ 
    printf("**error in exec"); 
    } 
} 
+0

工作過的:D非常感謝:D – gitter