2013-04-27 175 views
0

我試圖運行一段代碼將執行幾個UNIX命令,這些命令存儲在所述陣列lineArray其例如:lineArray = {"ls -l", "ls", "pwd", NULL};execvp將不執行命令

問題是此代碼只會打印出數組中的第一個命令,即使我已經在調試中看到我的函數根據execvp MAN正確解析命令及其參數。

任何形式的幫助將不勝感激。

int startProcesses(int background) { 
int i = 0; 
int j = 0; 
int pid; 
int status; 
char *copyProcessName[256]; 
int len, var=0; 

while(lineArray[i] != NULL) { 

    while(*(copyProcessName+var) != NULL) { 
     copyProcessName[var] = NULL; 
    } 

    j=0; 
    copyProcessName[j] = strtok(lineArray[i], " "); 
    while (copyProcessName[j] != NULL){ 
     j++; 
     copyProcessName[j] = strtok(NULL, " "); 
    } 


    pid = fork(); 

    if (pid == 0) { 
     // Child Process 
     execvp(copyProcessName[0], copyProcessName); 
     fflush(stdout); 
     i++; 
     continue; 

    } else if (!background) { 
     // Parent Process 
     waitpid(pid, &status, 0); 
     i++; 
     if(WEXITSTATUS(status)) { 
      printf(CANNOT_RUN_ERROR); 
      return 1; 
     } 
    } else { 
     i++; 
     continue; 
    } 
} 
return 0; 

}

+1

'len = strlen(copyProcessName);',有什麼想法? 'copyProcessName'是一個'char * [256]',所以它被轉換爲'char **'作爲'strlen'的參數。你的編譯器沒有抱怨過嗎?另外,如果'execvp'返回,孩子應該死亡,而不是'繼續'。 – 2013-04-27 12:07:57

回答

3

此代碼顯然是不對的:

len = strlen(copyProcessName); 
for (var = 0; var < len; ++var) { 
    copyProcessName[var] = NULL; 
} 

考慮到如果len可以是零,我們不知道什麼copyProcessName的內容實際上包含。

while(*(lineArray+i) != NULL) 

有什麼錯:

while(lineArray[i] != NULL) 

它的短,而且它是一個數組,所以你可能想使用[]索引它。

您還應該檢查返回值execvp(..) - 如果它返回,您將希望打印什麼是返回值,因爲這將表明您可能做錯了什麼。

在外環的第二次迭代,j不爲零,當你到下面的代碼,這可能會導致問題的所有方式:

copyProcessName[j] = strtok(lineArray[i], " "); 
while (copyProcessName[j] != NULL){ 
    j++; 
    copyProcessName[j] = strtok(NULL, " "); 
} 

這是不是有問題的確鑿名單你的代碼,就是我在相當快速地閱讀時發現的。

+1

啊,但是'*(array_name + index)'是非常吝嗇的。 – 2013-04-27 12:23:04

+0

你能否詳細解釋一下你的意思是關於execvp的返回值? – Steinfeld 2013-04-27 12:25:56

+0

閱讀手冊頁。它會說「如果有錯誤,返回值是-1,錯誤的原因存儲在'errno'」中。 – 2013-04-27 12:33:15