對於這個Shell程序,我使用函數strtok(見fragmenta.h代碼)來解析用戶引入的字符串。 我需要刪除strotk函數的空白,並介紹指針數組的結構。這是在fragmenta.h中進行的。Shell使用strtok和一個指針數組
在主程序(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使用。 – 2014-11-21 21:51:22
你能不能顯示fragmenta請願書 – 2014-11-21 21:51:51