为了更好地理解C,我正在制作一个小shell。我使用POSIX getline函数获取一个字符串,并通过空格将其拆分为令牌。但是当我调用execvp()来进行系统调用时,什么都没有发生。如果有人向我指出我的问题所在,显然我遗漏了一些可能很小的东西。(我没有包括整个代码,所以底部会缺少一些花括号,请忽略这个抱歉),非常感谢。
char *args[3]; // array for the command and arguments
cmd = strtok(line, " ");
args[0] = cmd; // put the first command in the array
for(int i = 1; i < whitespace+1; ++i){
cmd = strtok('\0', " \n");
args[i] = cmd; // fill the array of strings with the arguments
}
args[2] = '\0'; // assign last element to NULL
pid = fork();
if(pid != 0){
waitpid(-1, &stat, 0);
}
else{
char *const *test[1];
test[0] = '\0';
execvp("/bin/ls", test[0]);
execvp(args[0], &args[1]);最后是我遇到问题的地方,我分别尝试了两种版本的execvp,但都没有工作,我在这个问题上被困了两天。任何帮助都非常感谢
发布于 2014-11-13 20:22:09
下面是一个关于如何使execvp工作的最小示例。
#include <stdio.h>
#include <unistd.h>
int main( void )
{
char *test[2]; // declare an array of pointers
test[0] = "/bin/ls"; // first arg is the path to the executable
test[1] = NULL; // NULL terminator indicates no additional args
execvp( test[0], test );
}以下是execvp手册页的说明
按照约定,第一个参数应该指向与正在执行的文件相关联的文件名。指针数组必须以空指针结束。
https://stackoverflow.com/questions/26917428
复制相似问题