简体   繁体   English

移植使用双向popen()到POSIX的C ++代码的最佳方法

[英]Best way to port C++ code that uses a bidirectional popen() to POSIX

I'm trying to get some C++ code running on Linux that a colleague wrote for OS X. It's mostly portable, but there's one part I don't know how to handle. 我正在尝试在Linux上运行一些同事为OS X编写的C ++代码。它主要是可移植的,但有一部分我不知道如何处理。 He uses popen(CMD, "r+") to open a bidirectional pipe and communicates with the process through fget and fprint . 他使用popen(CMD, "r+")来打开双向管道,并通过fgetfprint与进程通信。

On Linux the type r+ is not available as pipes can only be unidirectional. 在Linux上,类型r+不可用,因为管道只能是单向的。 I guess usually the way would be to handle bidirectional communication through a socket but the called CMD is an interactive program over which we have only limited control. 我想通常的方法是通过套接字处理双向通信,但被叫CMD是一个交互式程序,我们只能通过有限的控制来实现。

After some searching I found some snippets for a popen2 implementation in C. It works kinda but it would be much easier if there would be a real "C++" way to do it using streams instead of low-level functions like write and read . 经过一些搜索后,我在C中找到了一些popen2实现的片段。它的工作方式有点但是如果有一种真正的“C ++”方法可以使用流而不是像writeread这样的低级函数来实现它会更容易。 Also I have some problems where a lot of communication gets missing. 我也有一些问题,很多沟通都丢失了。

Anyway, my question is: What is the best way to port code that uses bidirectional popen() to POSIX (or at least OS X + Linux)? 无论如何,我的问题是:使用双向popen()到POSIX(或至少OS X + Linux)的端口代码的最佳方法是什么?

socketpair(2) creates a pair of sockets that are endpoints of a bidirectional pipe. socketpair(2)创建一对作为双向管道端点的套接字。 This will directly replace popen() . 这将直接取代popen() I do not see why CMD being or not being an interactive program has anything to do with it. 我不明白为什么CMD成为一个交互式程序与它有什么关系。

It is possible that the program might need to have an actual terminal device (unlikely, since popen () doesn't really emulate one). 程序可能需要有一个实际的终端设备(不太可能,因为popen ()并不真正模拟一个)。 If so, the pty(7) man page provides additional documentation for creating a bi-directional pipe that drives a pseudo-tty device. 如果是这样, pty(7)手册页提供了用于创建驱动伪tty设备的双向管道的附加文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM