我试图运行一段代码将执行几个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