C ++ Linux交互另一个程序stdin/stdout [英] C++ Linux Interact Another Program stdin / stdout

查看:267
本文介绍了C ++ Linux交互另一个程序stdin/stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux中有一个可执行文件,可以与stdin/stdout交互.我正在尝试用C ++编写一个程序,该程序可以交互地调用该程序,将命令发送到其stdin并捕获其stdout.

I have an executable in Linux that can interact with stdin/stdout. I'm trying to write a program in C++ that can interactively call this program, send commands to its stdin, and capture it's stdout.

我一直很困惑.我不想派生我的程序(是吗?).我确实希望我的程序能够启动客户端",发送数据,获取输出,发送更多数据,获取更多输出,...以及关闭客户端".

I've been getting really confused. I don't want to fork my program (do I?). I do want my program to be able to start the "client", send data, get output, send more data, get more output, ..., and close the "client".

P.S.是的,我确定以前已经问过这个问题,但是我花了几个小时才真正抓到头-可能没有使用正确的关键字.

P.S. Yes, I'm sure this has been asked before, but I've spent a few hours really scratching my head- probably not using the correct keywords.

推荐答案

执行另一个程序的唯一方法是通过exec()系统调用之一.这是唯一的方法.而且,如您所知,exec()将执行程序替换为exec()指定的程序.发出exec()的进程将不再存在,新程序现在使用的是PID.

The only way to execute another program is via one of the exec() system calls. This is the only way. And, as you know, exec() replaces the executing program with the program specified by exec(). The process that issued the exec() will not exist any more, it's PID is now used by the new program.

因此,从逻辑上讲,除非您希望程序被该其他可执行文件替换,否则您的程序必须为fork(),并且子进程使用exec()来执行新的可执行文件.这是开始新流程并继续运行原始流程的传统方式.为此需要fork().

It therefore logically follows, that unless you want your program to be replaced by that other executable, your program must fork(), and the child process uses exec() to execute the new executable. This is the traditional way to start a new process, and continue running the original process. A fork() is required for that.

您描述的情况是非常典型的按数字绘制的情况,已经完成了无数次:

The situation you describe is fairly typical, paint-by-the-numbers situation, that's been done countless of times:

  1. 使用pipe()创建两个管道,一个用于管道标准输入,一个用于管道标准输出.

  1. Use pipe() to create two pipes, one for the piped stdin, one for the piped stdout.

使用fork().子进程dup2()将stdin管道的读取端设置为0,将stdout管道的写入端设置为1,关闭每个原始管道的两端,并exec()新建进程.

Use fork(). The child process dup2()s the read end of the stdin pipe to 0, the write end of the stdout pipe to 1, closes both ends of each of the original pipes, and exec()s the new process.

父进程关闭stdin管道的读取端,stdout管道的写入端,然后继续使用stdin管道的写端和stdout管道的读取端与子进程进行交互.

The parent process closes the read end of the stdin pipe, the write end of the stdout pipe, then proceeds to interact with the child process using the write end of the stdin pipe and the read end of the stdout pipe.

这篇关于C ++ Linux交互另一个程序stdin/stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆