老实说,我不知道以下情况是如何发生的。这是代码:
while(1)
{
char** line = read_command();
char* command = line[0];
char** parameters = malloc(100);
int i;
for(i = 0; i < pNum; i++) // pNum is a global var containing the number of words read from read_command()
{
parameters[i] = line[i];
printf("%i: %s", i, parameters[i]);
}
printf("%s\n", parameters[0]);
parameters[0] = "/usr/bin/";
strcat(parameters[0], command);
printf("%s\n", command);
printf("%s\n", parameters[0]);
if(fork() != 0)
waitpid(1, &status, 0);
else
execve(parameters[0], parameters, NULL);
}
read_command() 返回一个 char**,它基本上是输入字符串的“数组”,每个 char* 包含一个单词。就像我输入“hello people of earth”一样,结果将是 [“hello”、“people”、“of”、“earth”]。此功能始终有效。
在第一次迭代时,一切都按预期工作。例如,当我输入“日期”时,输出如下:
0: date
date
date
/usr/bin/date
and then the date is displayed
但是在第二次迭代中,如果我再次使用“日期”作为输入,则输出如下:
0:date
edate
/usr/bin/datedate
and the date command is not issued
即使我打印像“hello”这样的常量字符串,第二个 printf 语句也总是在第一次迭代后打印“e”。然后参数 [0] 以某种方式在其中包含 2 个“日期”,即使命令指针只有 1 个“日期”。
在第三次迭代之后,程序不等待用户输入,它只是不停地循环并显示“PM:警告,进程表已满!”
什么可能导致这种情况?
我在 MINIX 3.1.0 中使用 C 的 cc 编译器工作
编辑:read_command():
char* line = malloc(), * linep = line;
size_t lenmax = 100, len = lenmax;
int c;
int currPos = 0;
int currParam = 0;
int i;
char** parameters = malloc(100);
if(line == NULL)
return NULL;
while(1)
{
c = fgetc(stdin);
if(c == EOF) || c == '\n')
break;
if(--len == 0)
{
char* linen = realloc(linep, lenmax *= 2);
len = lenmax;
if(linen == NULL)
{
free(linep);
return NULL;
}
line = linen + (line - linep);
linep = linen;
}
if((*line++ = c) == '\n')
break;
}
*line = '\0'; // everything up to this point i got from this link: http://stackoverflow.com/a/314422/509914
parameters[currentParam] = malloc(100);
for(i = 0; i < strlen(linep); i++);
{
if(isspace(linep[i]) || line[i] == EOF)
{
parameters[currParam][currPos] = '\0;
currPos = 0;
parameters[++currParam] = malloc(100);
}
else
parameters[currParam][currPos++] = line[i];
}
parameters[currParam][currPos] = '\0';
pNum = currParam + 1;
return parameters;