您的问题是这temp
是一个单指针,您需要将一组指针传递给execvp()
.
就像是:
enum { MAX_ARGS = 64 };
char *args[MAX_ARGS];
char **next = args;
temp = strtok(line, " ");
while (temp != NULL)
{
*next++ = temp;
printf("%s\n", temp);
temp = strtok(NULL, " ");
}
*next = NULL;
execvp(args[0], args);
请注意,参数列表已被赋予一个空指针作为终止符,就像argv[argc] == NULL
in一样main()
。显然,我忽略了错误检查(如果传递的参数超过 63 个,就会溢出args
数组)。但这包含了核心思想。
在这个例子中,我似乎无法获得简单的命令ls
来工作,我已经尝试过mkdir
并且echo
它们似乎工作正常。传递ls
返回 -1 从execvp()
.
我不确定问题可能是什么——所有这些都对我有用:
ls
ls -l
ls -l madump.c
(madump.c
恰好是我正在测试的目录中的文件)
我使用的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
char line[1024];
while (fgets(line, sizeof(line), stdin) != NULL)
{
if (strcmp(line, "exit\n") == 0)
exit(EXIT_SUCCESS);
char *args[64];
char **next = args;
char *temp = strtok(line, " \n");
while (temp != NULL)
{
*next++ = temp;
printf("%s\n", temp);
temp = strtok(NULL, " \n");
}
*next = NULL;
puts("Checking:");
for (next = args; *next != 0; next++)
puts(*next);
execvp(args[0], args);
}
return EXIT_SUCCESS;
}
请注意,在创建一个名称末尾带有换行符的目录之后,我将其添加\n
到了令牌列表中。strtok()
适合烦人的朋友和困惑的半受过教育的敌人,但从大多数其他角度来看却是一种滋扰。execvp()
请注意我是如何在实际这样做之前打印出将要传递给的数据的。通常,我会使用printf("<<%s>>\n", *next);
而不是仅仅puts()
为了获得参数开始和结束的明确指示。
运行命令 ( doit
) 的输出是:
$ ./doit
ls -l madump.c
ls
-l
madump.c
Checking:
ls
-l
madump.c
-rw-r--r-- 1 jleffler staff 2352 Jul 28 2011 madump.c
$
你从你的版本中得到了什么?