如何从其他命令行接口程序获得输出
How to get output from other command line interface programs?
好的,我做了一些调查,但没有发现任何有用的东西。我正试图编写一个程序,将从iwconfig(在linux机器上)接收输入。然后,它将对输入进行排序,进行一些计算并输出到数据库。对输入和输出进行排序不是问题(或者我真的希望不是),但我正在努力从另一个命令行程序读取输入。我现在的基本Hello World程序是:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int numbr = 0;
cout << "Hello world!" << endl;
cin >> numbr;
cout << "number is " << numbr;
cout << system("iwconfig");
return 0;
}
然而,在运行程序时,它所做的只是输出hello world,请求我的随机输入并再次输出。它不输出iwconfig(我还将这行运行为system("iwconfig");没有输出语句)。有人会好心地解释我如何运行一个程序,如iwconfig和捕获它的输出?
"有没有人能解释一下我如何运行像iwconfig这样的程序并捕获它的输出?"
检查int system( const char *command );
文档。它当然不提供返回值,您想用cout
语句输出。
您可能希望在您的主程序和iwconfig
程序之间建立管道,如这里描述的,以控制子进程使用的输入和输出流。
复制上述答案改编:
int main() {
int fd_p2c[2], fd_c2p[2], bytes_read;
pid_t childpid;
char readbuffer[80];
string program_name = "iwconfig";
string receive_output = "";
if (pipe(fd_p2c) != 0 || pipe(fd_c2p) != 0) {
cerr << "Failed to pipen";
exit(1);
}
childpid = fork();
if (childpid < 0) {
cout << "Fork failed" << endl;
exit(-1);
}
else if (childpid == 0) {
if (dup2(fd_p2c[0], 0) != 0 ||
close(fd_p2c[0]) != 0 ||
close(fd_p2c[1]) != 0) {
cerr << "Child: failed to set up standard inputn";
exit(1);
}
if (dup2(fd_c2p[1], 1) != 1 ||
close(fd_c2p[1]) != 0 ||
close(fd_c2p[0]) != 0) {
cerr << "Child: failed to set up standard outputn";
exit(1);
}
execl(program_name.c_str(), program_name.c_str(), (char *) 0);
cerr << "Failed to execute " << program_name << endl;
exit(1);
}
else {
close(fd_p2c[0]);
close(fd_c2p[1]);
cout << "Writing to child: <<" << gulp_command << ">>" << endl;
int nbytes = gulp_command.length();
if (write(fd_p2c[1], gulp_command.c_str(), nbytes) != nbytes) {
cerr << "Parent: short write to childn";
exit(1);
}
close(fd_p2c[1]);
while (1) {
bytes_read = read(fd_c2p[0], readbuffer, sizeof(readbuffer)-1);
if (bytes_read <= 0) break;
readbuffer[bytes_read] = ' ';
receive_output += readbuffer;
}
close(fd_c2p[0]);
cout << "From child: <<" << receive_output << ">>" << endl;
}
return 0;
}
相关文章:
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 显示错误输出的简单数组排序程序
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 如何从Windows应用程序输出到标准?
- 我写了一个C++程序来模拟Enigma机器.我没有得到输出
- 如何使用C++读取另一个程序中的源代码输出
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 为什么这个程序的输出不如预期
- 在由Sublime文本3编译后在cmd上显示Java程序输出
- C++ 每次运行程序时我都会"nan"输出的问题
- 如何从 Win32 C++ 应用程序输出到父控制台窗口?
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 而循环:简单的除法程序输出零,不明白为什么
- 如何在 html 页面中插入 cgi 应用程序的输出?
- C 中的输出程序无明显的原因是白色的
- C++:更改简单输出程序的字体
- C++ 简单的输入/输出程序 + 枚举器
- C++字母等效数字代码输出程序
- 编译输出程序集