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

问题描述 投票:0回答:3

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

编辑:嗯,没有代码,没有人会知道,我正在尝试解决什么问题。实际上,没有输出(我正在使用my_process | proc2 | proc3s)

printf
c linux pipe stdout
3个回答
1
投票

请了解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]); } file descriptors系统调用。另外,检查piperead


1
投票

您的“独生子女”代码存在一些主要问题,最明显的是您将write命令配置为写入管道,而不是原始标准输出。它也没有关闭足够的文件描述符(管道的常见问题),并且如果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(),这也适用。

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

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


0
投票

作为F_DUPFD,你需要像Alex answeredpipe(2),也许是dup2(2)和其他一些poll(2)等系统调用。

阅读syscalls(2),它解释得很好......

另外,玩Advanced Linux Programming并研究一些简单的免费软件shell的源代码。

另见strace(1) - 在你的情况下还不够 -

回想一下,popen(3)流是缓冲的。你可能需要在适当的地方stdio(3)(例如在fflush(3)之前)

© www.soinside.com 2019 - 2024. All rights reserved.