为什么我的缓冲区没有连接?

Why is my buffer not concatenating?

如果 main 没有参数,那么我的程序应该 printenv | sort | less 并且我已经实现了该功能。如果 main 有参数,那么程序应该执行 printenv | grep <parameter list> | sort | less 而我的问题是调试不起作用。我可以在我的代码中尝试语句 printf,但它什么也没做。为什么?为什么我的要求的后半部分不起作用?程序有什么问题?

预期输出为 printenv | grep <parameter list> | sort | less。例如,我想查询环境变量,以便执行 a.out JOBS COMPIZ UPSTART 应该与 printenv | grep -e 'JOBS\|COMPIZ\|UPSTART' | sort | less.

执行相同的操作

相反,我在尝试分叉命令链时得到了意外的输出。

#include <sys/types.h> /* definierar bland annat typen pid_t */
#include <errno.h> /* definierar felkontrollvariabeln errno */
#include <stdio.h> /* definierar stderr, dit felmeddelanden skrivs */
#include <stdlib.h> /* definierar bland annat exit() */
#include <unistd.h> /* definierar bland annat fork() */

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];
        for( i=1; i<argc-1; i++)
        {
            sprintf(tmp, "%s%s%s", tmp, "|", argv[i]);
        }
        const char *printenv[] = { "printenv", 0};
        const char *grep[] = { "grep", "-E", tmp, NULL};
        const char *sort[] = { "sort", 0 };
        const char *less[] = { "less", 0 };

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




}

部分问题是您通过写入 argv[1] 来写入只读内存段(由于 tmp = argv[1] 语句)。事实上,您很可能写入超过 argv[1] 的大小,这进一步加剧了这种情况。相反,您应该将字符串连接到一个足够大的新的可写缓冲区。

要将字符串连接到 tmp 变量中,您可以使用类似于以下的代码:

    // Compute required buffer length
    int len = 1; // adds 1 to the length to account for the [=10=] terminating char
    for( i=1; i<argc; i++)
    {
      len += strlen(argv[i]) + 2; // +2 accounts for length of "\|"
    }

    // Allocate buffer
    tmp = (char*) malloc(len);
    tmp[0] = '[=10=]';
    // Concatenate argument into buffer
    int pos = 0;
    for( i=1; i<argc; i++)
    {
      pos += sprintf(tmp+pos, "%s%s", (i==1?"":"|"), argv[i]);
    }

    printf("tmp:%s", tmp);
    fflush(stdout); // force string to be printed

    ...
    free(tmp);

至于为什么没有出现输出,很可能是因为 printf 是行缓冲的。换句话说,它通常不会被打印,直到必须打印行尾 (\n) 或 fflush 明确强制将缓冲区打印到控制台。

注意:不要忘记free()变量tmp一旦你完成它。