所以我创建了一个名为 myargv 的 char** 变量,它应该像一个在每个索引处存储字符串的数组。我有一个函数可以将 char** 返回给 myargv,当我从内部打印所有内容时,该函数似乎工作正常,但是当我尝试从 main 打印出 myargv 中的内容时,它不再工作了.. .. 谁能帮我?
char **findArgs(char *line)
{
int i = 0;
char **temp, *tokTemp;
char **myargv;
tokTemp = strtok(line, " ");
myargv = malloc(sizeof(*myargv));
while (tokTemp != NULL)
{
if (strcmp(tokTemp, ">") == 0 || strcmp(tokTemp, "<") == 0 || strcmp(tokTemp, ">>") == 0)
{
break;
}
else
{
myargv[i] = malloc(strlen(tokTemp) + 1);
//myargv[i] = malloc(sizeof(char)*strlen(tokTemp));
strcpy(myargv[i], tokTemp);
//printf("myargv[%d] = %s \n", i, myargv[i]);
temp = realloc(myargv, (i+2)*sizeof(*myargv));
if (temp != NULL)
{
myargv = temp;
}
tokTemp = strtok(NULL, " ");
i++;
}
}
myargv[i] = NULL;
//printf("myargv[0] = %s\n", myargv[0]);
return myargv;
}
int main(int argc, char *argv[], char *env[])
{
int cmdInt, pid, status, i = 0, ioNumber = 0;
char input[64], lineBUFFER[64], lineBUFFER2[64], lineBUFFER3[64], lineBUFFER4[64], homePath[64], fileName[64], cmdPathFINAL[64];
char *cmd;
char **myargv, **cmdPath;
int myFile;
while(1)
{
printf("command: ");
gets(input);
strcpy(lineBUFFER, input);
strcpy(lineBUFFER2, input);
strcpy(lineBUFFER3, input);
strcpy(lineBUFFER4, input);
cmd = strtok(lineBUFFER3, " ");
cmdInt = findCommand(lineBUFFER2);
ioNumber = ioCheck(lineBUFFER4, fileName);
//printf("ioCheck = %d \n", ioNumber);
//printf("Filename: %s \n", fileName);
myargv = findArgs(lineBUFFER);
//printf("myargv[0] = %s\n", myargv[0]);
findHome(env, homePath);
//printf("Home path = %s\n", homePath);
switch(cmdInt)
{
case 0 :
if (myargv[1] == NULL)
{
chdir(homePath);
}
else
{
//printf("1st argument: %s, 2nd argument: %s, 3rd argument: %s \n", myargv[1], myargv[2], myargv[3]);
chdir(myargv[1]);
}
break;
case 1 :
exit(1);
break;
default :
pid = fork();
if (pid == 0)
{
//printf("Parent %d waits for child %d to die. \n", getpid(), pid);
pid = wait(&status);
printf("dead child = %d, how = %04x \n", pid, status);
exit(100);
}
else
{
ioNumber = ioCheck(lineBUFFER4, fileName);
//printf("ioCheck = %d \n", ioNumber);
//printf("Filename: %s \n", fileName);
cmdPath = getPath2(env);
//printf("cmdPath[0] = %s\n", cmdPath[0]);
findPath(cmd, cmdPath, cmdPathFINAL);
printf("Command Path = %s\n", cmdPathFINAL);
if (ioNumber == 1)
{
close(0);
myFile = open(fileName, O_RDONLY);
}
else if (ioNumber == 2)
{
close(1);
myFile = open(fileName, O_WRONLY|O_CREAT, 0644);
}
else if (ioNumber == 3)
{
close(1);
myFile = open(fileName, O_WRONLY|O_APPEND);
}
execve(cmdPathFINAL, myargv, env);
//printf("child %d dies by exit () \n", getpid());
exit(100);
}
break;
}
}
if (ioNumber == 1 || ioNumber == 2 || ioNumber == 3)
{
close(myFile);
}
return 0;
}