首页 文章

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

提问于
浏览
18
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' 的任何技巧,比如使用 \''\| 用于 | ?特殊字符?但我也试过了:(

3 回答

  • 5

    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 的另一种方法是启动两个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();
    
  • 7

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

    p1.start("/bin/sh -c \"ifconfig | grep inet\"");
    
  • 38

    您似乎无法在QProcess中使用管道符号 .

    但是有setStandardOutputProcess方法将输出传递给下一个进程 .

    API中提供了一个示例 .

相关问题