2014-09-28 130 views
-1

我正在使用C語言編寫一個用於學校項目的shell,但這個問題比您想象的要少得多。問題在於,當我輸入命令時,例如ls,輸出顯示在整個shell循環開始時顯示的下一個shell>提示之後。外殼看起來像:在下一個shell提示符後顯示Unix命令輸出

shell>ls 
shell>Debug shell.c 

我的代碼:

int main(){ 

    char line[255]; 

    while (1){ 
      printf("shell>"); 
      fgets(line, 255, stdin); 
      if (strcmp(line, "exit\n") == 0){ 
       break; 
      } 
      else{ 
       char* args[255]; 
       size_t n = 0; 
       for (char* ptr = strtok(line, " \n"); ptr; ptr = strtok(NULL, " \n")){ 
        if (n >= 255){ 
         break; 
        } 
        args[n++] = ptr; 
       } 
       args[n++] = NULL; 
       for (size_t i = 0; i != n; ++i){ 
        //printf("Token %zu is '%s'.\n", i, args[i]); 
       } 
       int pid = fork(); 
       if (pid == 0){ 
        //child process code 
        int flag = execvp(args[0], args); 
        if (flag < 0){ 
         perror("execvp failed"); 
        } 
       } 
       else{ 
        //parent process code 
        pid_t wait_pid(pid); 
       } 
      } 
    } 
    return 0; 
} 

所有其他錯誤之外,是什麼導致要顯示的輸出這樣?

回答

0

pid_t wait_pid(pid);是錯的,它不叫wait_pid。在調用函數時,您不指定返回類型。相反,嘗試:

pid_t result_pid = wait_pid(pid); 
// add error handling etc here, check man page for return value details 

而且因爲你實際上並沒有等待孩子的過程中,家長進行立即打印提示,爲您看到的輸出。

+0

謝謝,清理了一些東西 – 2014-09-28 19:11:23

相關問題