gpt4 book ai didi

c++ - 命令在终端中工作,但不是通过 QProcess

转载 作者:IT老高 更新时间:2023-10-28 21:54:14 24 4
gpt4 key购买 nike

ifconfig | grep 'inet'

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

我的示例代码是

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

textedit 上没有显示任何内容。

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

最佳答案

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

有三种可能的解决方案:

-c(“command”)之后将你想执行的命令作为参数放到sh中:

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 的方法是启动两个 QProcess 并在代码中进行管道处理:

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();

关于c++ - 命令在终端中工作,但不是通过 QProcess,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10701504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com