我試圖運行一段代碼將執行幾個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;
}
'len = strlen(copyProcessName);',有什麼想法? 'copyProcessName'是一個'char * [256]',所以它被轉換爲'char **'作爲'strlen'的參數。你的編譯器沒有抱怨過嗎?另外,如果'execvp'返回,孩子應該死亡,而不是'繼續'。 – 2013-04-27 12:07:57