【发布时间】:2019-06-07 05:35:32
【问题描述】:
我正在尝试使用自定义**tokens 双指针作为输入来执行execvp(),而不是在“创建自定义外壳”分配中使用argv[],如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
char *token;
char **tokens = malloc(sizeof(char*)*512); //512 is for the maximum input-command length
char *command=malloc(sizeof(char)*512);
int i = 0;
pid_t child_pid;
int status;
//***********take input from user*************************************
fgets(command,512,stdin);
//***********parse input*********************************************
token = strtok(command," \t");
while( token != NULL ) {
tokens[i]=token;
i ++;
token = strtok(NULL, " \t");
}
child_pid = fork();
if(child_pid == 0) {
/* This is done by the child process. */
execvp(tokens[0], tokens);
} else {
waitpid(child_pid, &status, WUNTRACED);
}
}
问题肯定出在这一行:
execvp(tokens[0], tokens);
我就是不明白为什么不能执行并打印到我的 stdout。
我试过这个:
execvp("ls", tokens);
它工作得很好。 还有这个:
printf("%s\n", tokens[0]);
输出为(根据测试输入:ls):
ls
【问题讨论】:
-
char **tokens = malloc(sizeof(char)*512);大小参数不正确。tokens[i]=token;令牌数组应以空指针终止。 -
我尝试将这一行放在
while循环之后:`tokens[i] = NULL;` 仍然不起作用 -
提供的代码从未将值分配给
child_pid。如果那是一个局部变量,那么在您测试它时它的值是不确定的。在检查 pid 之前,您的意思是child_pid = fork();吗? -
这里不需要
WUNTRACED选项。第三个参数使用 0。
标签: c shell execvp double-pointer