[英]execvp won't execute a command
我正在嘗試運行一段代碼,該代碼將執行一些UNIX命令,這些命令存儲在lineArray數組中,例如: lineArray = {"ls -l", "ls", "pwd", NULL};
問題是即使我在調試中看到我的函數根據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);
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, " ");
}
這不是您的代碼問題的最終列表,這只是我在快速閱讀它時發現的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.