QProcess 执行一个单一的进程。你想要做的是执行一个shell 命令,而不是一个进程。命令的管道是 shell 的一个特性。
有三种可能的解决方案:
将要执行的命令作为参数放在sh
after -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();