gpt4 book ai didi

c - execvp 不会执行命令

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:17 25 4
gpt4 key购买 nike

我正在尝试运行一段将执行一些 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, " ");
}

这不是您的代码问题的最终列表,只是我在快速阅读代码时发现的问题。

关于c - execvp 不会执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16251893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com