2015-02-07 58 views
0
int shell (int argc, char *argv[]) { 
    char *s = malloc(INPUT_STRING_SIZE+1);   /* user input string */ 
    tok_t *t;   /* tokens parsed from input */ 
    int lineNum = 0; 
    int fundex = -1; 
    pid_t pid = getpid();  /* get current processes PID */ 
    pid_t ppid = getppid(); /* get parents PID */ 
    pid_t cpid, tcpid, cpgid; 

    init_shell(); 

    printf("%s running as PID %d under %d\n",argv[0],pid,ppid); 

    lineNum=0; 

    const int BUF_SIZE = 200; 
    char buf[BUF_SIZE]; 
    getcwd(buf, BUF_SIZE); 

    fprintf(stdout, "%d %s: ", lineNum++, buf); 
    while ((s = freadln(stdin))){ 
    char *ptrA, *ptrB; 
    ptrA = strstr(s, "<"); 
    ptrB = strstr(s, ">"); 
    if (ptrA) { 
     *ptrA = '\0'; 
     ptrA++; 
    } 
    if (ptrB) { 
     *ptrB = '\0'; 
     ptrB++; 
    } 
    if (ptrA && ptrB) { 

    } else if (ptrA) { 

    } else if (ptrB) { 
     size_t ln = strlen(ptrB) - 1; 
     if (ptrB[ln] == '\n') // get rid of the trailing newline 
      ptrB[ln] = '\0'; 
     int newfd; /* new file descriptor */ 
     if ((newfd = open(ptrB, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR|S_IXUSR)) < 0) { 
     perror("Can't open outfile file\n"); /* open failed */ 
     exit(1); 
     } 
     printf("newfd: %d\n", newfd); 
     dup2(newfd, 1); 
     printf("Here\n"); 
    } 
    printf("%s\n", s); 
    t = getToks(s); /* break the line into tokens */ 
    fundex = lookup(t[0]); /* Is first token a shell literal */ 
    if(fundex >= 0) { 
     cmd_table[fundex].fun(&t[1]); 
    } else { 
     char *bin; 
     if (get_binary(t[0], &bin) == 0) { 
     t[0] = bin; 
     } 
     pid_t child_pid = fork(); 
     int exit_code; 
     if (child_pid == 0) { 
     execv(t[0], &t[0]); 
     } else { 
     wait(&exit_code); 
     } 
    } 
    getcwd(buf, BUF_SIZE); 
    fprintf(stdout, "%d %s: ", lineNum++, buf); 
    } 
    return 0; 
} 

我測試了我的外殼,wc shell.c>test和發生的事情是,我得到一個空行的終端上,如果它在等待我的輸入。當我按Enter時,它會發生段錯誤。如果我將dup2行註釋掉,那麼shell可以很好地工作(當然,不用重定向)。我在Windows上使用Cygwin,如果有幫助的話。DUP2導致程序中止

+0

你的'exec'系統調用在哪裏? – 2015-02-07 05:59:53

+0

我相信我在錯誤的地方有dup。我把它移到execv調用之前,現在我沒有發生段錯誤。但輸出仍然打印到終端。 – JamesGold 2015-02-07 06:30:40

+0

沒關係。它現在有效。 – JamesGold 2015-02-07 06:33:18

回答

0

我把我的dup放在了錯誤的地方。我分叉後需要重做,但在我執行之前。