C管道Comand中的Minishell仅带一个管道

时间:2018-11-27 19:04:05

标签: c shell ubuntu pipe pipeline

我正在尝试制作一个微型外壳程序,该外壳程序可以执行用管道传输的命令,而我只能使用一个管道。我使用具有以下类型和功能的解析器:

typedef struct {
    char * filename;
    int argc;
    char ** argv;
} tcommand;

typedef struct {
    int ncommands;
    tcommand * commands;
    char * redirect_input;
    char * redirect_output;
    char * redirect_error;
    int background;
} tline;

extern tline * tokenize(char *str);

这是我的主要功能代码:

int main() {

    char buf[1024];
    int i, j;


    system("clear");

    printf("msh>");
    while (fgets(buf, 1024, stdin)) {
        line = tokenize(buf);
        if (line == NULL){
            continue;
        }

        comandos = line->commands;
        ncomands = line->ncommands;

        if (ncomands == 1) {
            if (strcmp(comandos[0].argv[0], "exit") == 0) {
                salir();
            }
            if (strcmp(comandos[0].argv[0], "cd") == 0) {
                cd(comandos[0].argc, comandos[0].argv);
            }else {

            }
        }else{
            printf("Voy a ejecutar %d comandos\n", ncomands);
            tcommand *recorrerComandos = comandos;
            int argc = 0;
            char **recorrerArgumentos;
            for (i = 0; i < ncomands; i++){
                argc = recorrerComandos[i].argc;
                recorrerArgumentos = recorrerComandos[i].argv;
                printf("Comando %d: %s\n",i,recorrerArgumentos[0]);
                for(j=1; j < argc; j++){
                    printf("Argumnento %d: %s\n",j,recorrerArgumentos[j]);
                }
                printf("***************************************\n");
            }
            /*This is the call that does not work */
            pipes(ncomands, comandos);
        }
        printf("msh>");
    }
    printf("\n");
    return 0;
}


void proceso(int in, int out, tcommand comando) {
    static int i = 0;
    i++;
    printf("Ejecuto comando %d\n",i);
    pid_t pid;
    pid = fork();
    if (pid == 0) {
        if (in != 0) {
            dup2(in, 0);
            close(in);
        }

        if (out != 1) {
            dup2(out, 1);
            close(out);
        }

        execvp(comando.argv[0], comando.argv);
        fprintf(stderr, "Error al ejecutar el comando: %s\n", comandos[0].argv[0]);
        exit(errno);
    }
}

void pipes(int ncomands, tcommand * comandos) {
    int i;
    pid_t pid;
    int in, fd[2];

    in = 0;

    for (i = 0; i < ncomands - 1; ++i) {

        pipe(fd);

        proceso(in, fd[1], comandos[i]);

        close(fd[1]);

        in = fd[0];
    }


    if (in != 0)
        dup2(in, 0);

    execvp(comandos[i].argv[0],comandos[i].argv);
}

如果我运行它并输入ls | grep hola,则退出为

msh>ls | grep hola
Voy a ejecutar 2 comandos
Comando 0: ls
***************************************
Comando 1: grep
Argumnento 1: hola
***************************************
Ejecuto comando 1

我不知道我在哪里犯了错误。预先谢谢你

0 个答案:

没有答案