21
ifconfig | grep 'inet'

通过终端执行时正在工作。但不是通过 QProcess

我的示例代码是

QProcess p1;
p1.start("ifconfig | grep 'inet'");
p1.waitForFinished();
QString output(p1.readAllStandardOutput());
textEdit->setText(output);

textedit 上没有显示任何内容。

但是当我ifconfig在 qprocess 开始时使用时,输出会显示在 textedit 上。我是否错过了构造命令的任何技巧ifconfig | grep 'inet',例如使用\'for'\|for |?对于特殊字符?但我也试过了:(

4

3 回答 3

48

QProcess 执行一个单一的进程。你想要做的是执行一个shell 命令,而不是一个进程。命令的管道是 shell 的一个特性。

有三种可能的解决方案:

将要执行的命令作为参数放在shafter -c("command") 中:

QProcess sh;
sh.start("sh", QStringList() << "-c" << "ifconfig | grep inet");

sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();

或者您可以将命令作为标准输入写入sh

QProcess sh;
sh.start("sh");

sh.write("ifconfig | grep inet");
sh.closeWriteChannel();

sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();

另一种避免的方法sh是启动两个 QProcesses 并在您的代码中进行管道:

QProcess ifconfig;
QProcess grep;

ifconfig.setStandardOutputProcess(&grep); // "simulates" ifconfig | grep

ifconfig.start("ifconfig");
grep.start("grep", QStringList() << "inet"); // pass arguments using QStringList

grep.waitForFinished(); // grep finishes after ifconfig does
QByteArray output = grep.readAll(); // now the output is found in the 2nd process
ifconfig.close();
grep.close();
于 2012-05-22T11:59:00.570 回答
9

QProcess对象不会自动为您提供完整的 shell 语法:您不能使用管道。为此使用外壳:

p1.start("/bin/sh -c \"ifconfig | grep inet\"");
于 2012-05-22T11:58:50.960 回答
6

您似乎不能在 QProcess 中使用管道符号。

但是,有setStandardOutputProcess方法将输出传送到下一个进程。

API 中提供了一个示例。

于 2012-05-22T12:01:33.640 回答