如何管道自己的输出到另一个进程?

时间:2014-08-19 13:14:24

标签: c linux pipe stdout

我想做一些简单的事情:my_process | proc2 | proc3,但是以编程方式 - 不使用shell,这可以很容易地做到这一点。这可能吗?我找不到任何东西:(

修改 好吧,没有代码,没有人会知道,我试图解决什么问题。实际上,没有输出(我使用printf s)

int pip1[2];
pipe(pip1);

dup2(pip1[1], STDOUT_FILENO); 
int fres = fork();

if (fres == 0) {
    close(pip1[1]);
    dup2(pip1[0], STDIN_FILENO);
    execlp("wc", "wc", (char*)0);
}
else {
    close(pip1[0]);
}

3 个答案:

答案 0 :(得分:1)

请了解file descriptorspipe系统调用。另外,请检查readwrite

答案 1 :(得分:1)

你的一个孩子'代码有一些主要问题,最明显的是您将wc命令配置为写入管道,而不是原始标准输出。它也没有关闭足够的文件描述符(管道的常见问题),如果fork()失败,也不够小心。

你有:

int pip1[2];
pipe(pip1);

dup2(pip1[1], STDOUT_FILENO);      // The process will write to the pipe
int fres = fork();                 // Both the parent and the child will…
                                   // Should handle fork failure
if (fres == 0) {
    close(pip1[1]);
    dup2(pip1[0], STDIN_FILENO);   // Should close pip1[0] too
    execlp("wc", "wc", (char*)0);
}
else {                             // Should duplicate pipe to stdout here
    close(pip1[0]);                // Should close pip1[1] too
}

你需要:

fflush(stdout);    // Print any pending output before forking

int pip1[2];
pipe(pip1);

int fres = fork();

if (fres < 0)
{
    /* Failed to create child */
    /* Report problem */
    /* Probably close both ends of the pipe */
    close(pip1[0]);
    close(pip1[1]);
}
else if (fres == 0)
{
    dup2(pip1[0], STDIN_FILENO);
    close(pip1[0]);
    close(pip1[1]);
    execlp("wc", "wc", (char*)0);
}
else
{
    dup2(pip1[1], STDOUT_FILENO);
    close(pip1[0]);
    close(pip1[1]);
}

请注意,修改后的代码如下:

经验法则:如果您使用dup2()将管道的一端复制到标准输入或标准输出,则应关闭的两个端原管。

如果您将dup()fcntl()F_DUPFD一起使用,这也适用。

结果是,如果您不将管道的一端复制到标准I / O通道,您通常不会关闭管道的两端(尽管您通常仍然关闭一端)直到你完成了沟通。

如果您想要恢复管理,可能需要考虑在运行管道之前保存原始标准输出。

答案 2 :(得分:0)

作为Alex answered,您需要pipe(2)dup2(2),或许poll(2)以及其他syscalls(2)等系统调用。

阅读Advanced Linux Programming,它解释得非常好......

另外,玩strace(1)并研究一些简单的免费软件shell的源代码。

另见popen(3) - 在你的情况下还不够 -

回想一下,stdio(3)流是缓冲的。您可能需要在适当的位置fflush(3)(例如在fork(2)之前)