Sca*_*ode 19 c++ linux terminal qt pipe
ifconfig | grep 'inet'
Run Code Online (Sandbox Code Playgroud)
通过终端执行时正在工作.但不是通过QProcess
我的示例代码是
QProcess p1;
p1.start("ifconfig | grep 'inet'");
p1.waitForFinished();
QString output(p1.readAllStandardOutput());
textEdit->setText(output);
Run Code Online (Sandbox Code Playgroud)
textedit上没有显示任何内容.
但是当我ifconfig在qprocess开始使用时,输出会显示在textedit上.我错过任何计谋构建命令ifconfig | grep 'inet',如使用\'了'和\|为|?特殊字符?但我也试过了:(
lee*_*mes 41
QProcess执行一个进程.您要做的是执行shell命令,而不是进程.命令管道是shell的一个特性.
有三种可能的解决方案:
将要执行的命令作为参数添加到shafter -c("command"):
QProcess sh;
sh.start("sh", QStringList() << "-c" << "ifconfig | grep inet");
sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();
Run Code Online (Sandbox Code Playgroud)
或者您可以将命令编写为标准输入sh:
QProcess sh;
sh.start("sh");
sh.write("ifconfig | grep inet");
sh.closeWriteChannel();
sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();
Run Code Online (Sandbox Code Playgroud)
另一种避免的方法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();
Run Code Online (Sandbox Code Playgroud)
该QProcess对象不会自动为您提供完整的shell语法:您不能使用管道.为此使用shell:
p1.start("/bin/sh -c \"ifconfig | grep inet\"");
Run Code Online (Sandbox Code Playgroud)