为什么扩展grep无法正常工作?

时间:2015-04-03 16:12:57

标签: c linux shell pipe

当我像这样尝试扩展grep时,它不起作用。

const char *grep[] = { "grep", "-E", "'JOBS|COMPIZ'" };

如果我只为一个没有单引号的字符串这样做,那么它可以工作。为什么?为什么我不能像上面那样建立扩展grep的参数?以下只有一个字符串正在运行。

const char *grep[] = { "grep", "-E", "JOBS" };

我的程序应该printenv | sort | grep <parameter-list> | less,如果没有关于main的参数,那么程序应该printenv | sort | less。我已经实现了后一个功能,现在我需要实现参数列表的grep,但我似乎无法从C代码中扩展grep。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct command
{
    const char **argv;
};

int
spawn_proc (int in, int out, struct command *cmd)
{
    pid_t pid;

    if ((pid = fork ()) == 0)
    {
        if (in != 0)
        {
            dup2 (in, 0);
            close (in);
        }

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

        return execvp (cmd->argv [0], (char * const *)cmd->argv);
    }

    return pid;
}

int
fork_pipes (int n, struct command *cmd)
{
    int i;
    pid_t pid;
    int in, fd [2];

    /* The first process should get its input from the original file descriptor 0.  */
    in = 0;

    /* Note the loop bound, we spawn here all, but the last stage of the pipeline.  */
    for (i = 0; i < n - 1; ++i)
    {
        pipe (fd);

        /* f [1] is the write end of the pipe, we carry `in` from the prev iteration.  */
        spawn_proc (in, fd [1], cmd + i);

        /* No need for the write and of the pipe, the child will write here.  */
        close (fd [1]);

        /* Keep the read end of the pipe, the next child will read from there.  */
        in = fd [0];
    }

    /* Last stage of the pipeline - set stdin be the read end of the previous pipe
       and output to the original file descriptor 1. */
    if (in != 0)
        dup2 (in, 0);

    /* Execute the last stage with the current process. */
    return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}

int
main (int argc, char ** argv)
{
    printf("in main...");
    int i;

    if (argc == 1) {
        const char *printenv[] = { "printenv", 0};
        const char *sort[] = { "sort", 0 };
        const char *less[] = { "less", 0 };

        struct command cmd [] = { {printenv}, {sort}, {less} };
        return fork_pipes (3, cmd);
    }
    if (argc > 1) {
    /*char *tmp = argv[1];
    sprintf(tmp, "%s%s", "'", tmp);*/
        for( i=1; i<argc-1; i++)
        {
           /* tmp = "%s%s%s", tmp, "\\|", argv[i];
            printf("tmp:%s", tmp);
        sprintf(tmp, "%s%s%s", tmp, "|", argv[i]);
        sprintf(tmp, "%s%s", tmp, "'");*/
        }

        const char *printenv[] = { "printenv", 0};
        const char *grep[] = { "grep", "-E", "JOB" };
        const char *sort[] = { "sort", 0 };
        const char *less[] = { "less", 0 };

        struct command cmd [] = { {printenv}, {grep}, {sort}, {less} };
        return fork_pipes (4, cmd);
    }




}

1 个答案:

答案 0 :(得分:4)

不要在参数中使用单引号。仅在命令行上需要它们以防止shell解释垂直条。