C中从管道传递的参数

C中从管道传递的参数,c,pipe,C,Pipe,我正试图通过管道传递令牌并执行。。。但是,我的问题是,第一个子进程和第二个子进程接收相同的令牌。。。如果有第三个或更多代币,该怎么办 int pipedes[2]; pipe(pipedes); pid_t pid = fork(); if (pid == 0) { dup2(filedes[1], 1); execvp(argv[0], argv); } else { close

我正试图通过管道传递令牌并执行。。。但是,我的问题是,第一个子进程和第二个子进程接收相同的令牌。。。如果有第三个或更多代币,该怎么办

    int pipedes[2];
    pipe(pipedes);

    pid_t pid = fork();
    if (pid == 0) {
            dup2(filedes[1], 1);

            execvp(argv[0], argv);
    } else {
            close(pipedes[1]);
    }

    pid = fork();
    if (pid == 0) {
            dup2(pipedes[0], 0);

            execvp(arg[0], argv);
    }

    wait(&pid);
和代币

strtok(line, "|");

            pipe(line);
            while (1) {

                    line= strtok(NULL, "|");

                    pipe(line);
            }
这一行:

pipe(line);
这是胡说八道。它创建两个新的文件描述符,并用它们覆盖
的第一个
2xsizeof(int)
字节。生产者进程应该将令牌写入stdout,消费者进程应该从stdin读取令牌


顺便说一下,您的子进程似乎执行与父进程相同的可执行文件,并且参数完全相同。每个进程如何知道它是生产者还是消费者?

如果希望两个不同的子进程执行相同的可执行文件,但使用两个不同的命令,则需要为每个子进程设置两个不同的管道。设置管道的过程也不正确,因为您允许孩子打开管道

#include <sys/wait.h>
#include <unistd.h>
#include <
int pipedes_child_1[2];
int pipedes_child_2[2];

pipe(pipedes_child_1);

pid_t child = fork();

if (!child)
{
    dup2(pipedes_child_1[0], 0);
    close(pipedes_child_1[1]); //without this, child with hang on read()
    execvp(argv[0], argv);
}
else
{
    close(pipedes_child_1[0];
}

pipe(pipedes_child_2);

child = fork();

if (!child)
{
    dup2(pipedes_child_2[0], 0);
    close(pipe_des_child_2[1]);  //without this, child with hang on read()
    execvp(argv[0], argv);
}
else
{
    close(pipedes_child_2[0]);
}

//...write tokens to each child via pipedes_child_X[1];

//wait for all the children
int return_val = 0;
while(wait(&return_val) > 0 || errno != EINTR);

这是无效的代码,请检查手册页。嗯,目前我使用Tokinzizer命令子进程执行不同的令牌。有可能吗?我想你误解了管道的用途和工作方式。创建管道时,会得到一个读文件描述符和一个写文件描述符。写入写入文件描述符的所有内容都可以从读取描述符中读取。你需要两个管道,每个孩子一个,你需要交替给他们写信。
//child_1 executable that will take no arguments and read from the pipe
execlp(argv[1], argv[1], (char*)0);

//child_2 executable that will take no arguments and read from the pipe
execlp(argv[2], argv[2], (char*)0);