2011-01-20 28 views
1

我正在爲一個操作系統類構建一個shell,它必須使用exec()或其一個變體來執行外部命令。目前,我正在使用execlp(command,command_parameters, (char *) NULL)。這運行命令就好了(例如ls返回一個標準的目錄列表),但似乎沒有解析任何參數(例如運行mkdir hello會引發錯誤「hello:missing operand ...嘗試'hello --help'for 。更多信息)我在想什麼C execlp()沒有正確解析參數字符串

  else // Try to handle an external command 
     { 
      char *command_parameters = malloc(sizeof(raw_command)-sizeof(command)); 
      strcpy(command_parameters, raw_command+strlen(command)+1); 
      pmesg(1, "Command is %s.\n", command); 
      pmesg(1, "The command parameters are %s.\n", command_parameters); 
      pid_t pid = fork(); 
      pmesg(1, "Process forked. ID = %i. \n", pid); 
      int status; 
      if (fork < 0) 
      { 
       printf("Could not fork a process to complete the external command.\n"); 
       exit(EXIT_FAILURE); 
      } 
      if (pid == 0) // This is the child process 
      { 
       pmesg(1, "This is the child process, running execlp.\n"); 
       if (execlp(command, command_parameters, (char *) NULL) < 0) 
       { 
        printf("Could not execute the external command.\n"); 
        exit(EXIT_FAILURE); 
       } 
       else { pmesg(1, "Executed the child process.\n"); } 
      } 
      else {while(wait(&status) != pid); } // Wait for the child to finish executing 
      pmesg(1, "The child has finished executing.\n"); 
     } 

pmesg是一個調試標籤,打印)給予一定的調試級別的聲明

感謝

回答

3

幾個問題在這裏?!

  1. execlp(const char *file, const char *arg, ...)需要將參數分開並單獨傳遞,而不是一個大字符串。
  2. 按照慣例,第一個參數(在const char *file之後)是您正在運行的可執行文件的名稱,它在被調用的程序中被放入argv[0]。因此,第一個參數需要在此之後。

如:

execlp(command, command, arg1, arg2, ..., (char *)NULL); 

你所擁有的東西,做它喜歡:

execlp(command, command, command_parameters, (char *)NULL); 

可能,原樣,照顧你的問題與"mkdir", "hello",但你仍然不會將command_parameters字符串分開,所以如果不修改具有多個參數的命令,它將無法正常工作。

編輯:P.S.你行

if (fork < 0) 

應該

if (pid < 0) 
+0

什麼是鑄造字符指針爲NULL的含義是什麼? – 2016-10-14 08:12:05