【发布时间】:2014-11-21 21:40:03
【问题描述】:
对于这个 Shell 程序,我使用函数 strtok(参见 fragmenta.h 代码)来解析用户引入的字符串。 我需要使用 strok 函数删除空格并将它们引入指针数组的结构中。这是在fragmenta.h中制作的
在主程序(shell.c)中,需要引入字符串,这个被传递给fragmenta并存储在char **arg中。之后,我使用 execvp 函数来执行命令。
问题是程序存储了整个命令,但只执行第一个单独的命令。例如,如果我们引入“ls -al”,只执行 ls 命令,所以我理解这是指针的问题。
主程序shell.c
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include "fragmenta.h"
//
char cadena[50];
int pid;
int i, status;
char **arg;
pid_t pid;
//
main()
{
printf("minishell -> ");
printf("Introduce the command \n");
scanf("%[^\n]", cadena);
if (strcmp(cadena, "exit") == 0)
{
exit(0);
}
else
{
pid = fork();
if (pid == -1)
{
printf("Error in fork()\n");
exit(1);
}
else if (pid == 0) //child proccess
{
arg = fragmenta(cadena);
if (execvp(*arg, arg) < 0) /* execute the command */
{
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else /* for the parent: */
{
while (wait(&status) != pid);
}
}
}
int len;
char *dest;
char *ptr;
char *aux;
char **fragmenta(const char *cadena)
{
//
char *token;
int i = 0;
//
len = strlen(cadena);
char *cadstr[len + 1];
dest = (char *)malloc((len + 1) * sizeof(char));
strcpy(dest, cadena);
//printf("Has introducido:%s\n",dest);
token = strtok(dest, " ");
while ( token != NULL)
{
cadstr[i] = malloc(strlen(token) + 1);
strcpy(cadstr[i], token);
token = strtok(NULL, " ");
i++;
}
*cadstr[i] = '\0';
ptr = *cadstr;
i = 0;
while (cadstr[i] != NULL)
{
//printf("almacenado: %s\n",cadstr[i]);
i++;
}
return &ptr;
}
【问题讨论】:
-
使用
fgets而不是scanf。scanf是一个可以使用的 PITA。 -
你能显示片段吗