Qt QProcess基于Linux的命令管道符号无效问题【已解决】

QProcess基于Linux的命令管道符号无效问题

一、问题描述

  • 基于Linux环境,在Qt中使用QProcess start带管道符号|的命令,无异常但不会得到预期结果,将命令复制到终端中执行正常。代码如下所示:
bash 复制代码
    QString cmd = QString("命令1 | 命令2");
    qDebug() << cmd;
    process.start(cmd);

Linux管道符号|用于将前一个命令的输出作为后一个命令的输入,实现命令间的数据传递。它属于匿名管道(Anonymous Pipe),仅在内存中创建,作为临时通道,不依赖磁盘文件,且数据从左到右流动,不可逆向。管道主要用于组合简单命令,实现复杂的数据处理流程。

二、解决方案

2.1 问题原因

QProcess是Qt框架中用于启动外部程序并与它们交互的类,只能启动一个进程,输入"命令1 | 命令2",QProcess只能识别命令1,无法识别管道符号,会将| 命令2识别成命令1的参数。

2.2 解决方案

以下是解决方案:

    1. 调用bash,将上述代码的QString("命令1 | 命令2")替换为QString("bash -c \"命令1 | 命令2\"")
    1. 运行两次两次QProcess...
    1. QProcess进阶用法,使用process.setStandardOutputProcess(&xxx);函数

三、例程

3.1 解决方案例程

    1. 调用bash
cpp 复制代码
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[])
{
    QProcess process;

    QString tar_cmd = QString("bash -c \"cat Makefile | grep LIB > cs.txt \"");
    qDebug() << tar_cmd;
    process.start(tar_cmd);

    if (!process.waitForStarted()){
        qDebug() << "start failed";
        return false;
    }
    if (!process.waitForFinished(-1)){
        qDebug() << "run failed" << process.errorString();
        return false;
    }

}
    1. 调用两次QProcess,省略
    1. 使用process.setStandardOutputProcess(&xxx);函数
cpp 复制代码
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[])
{
    QProcess process1;
    QProcess process2;

    process1.setStandardOutputProcess(&process2);
    process1.start("cat Makefile");

    process2.setProcessChannelMode(QProcess::ForwardedChannels);
    process2.start("bash -c \"grep LIB > cs.txt\"");

    if(!process1.waitForStarted())
        return 0;
    process1.waitForFinished();
    process2.waitForFinished();
}

3.2 官方例程

官方文档:void QProcess::setStandardOutputProcess(QProcess *destination) - 这个函数是在Qt 4.2中引入

  • 将此进程的标准输出流通过管道传输到目标进程的标准输入。
    带管道的Shell命令 command1 | command2,可以使用QProcess通过以下代码完成:
cpp 复制代码
  QProcess process1;
  QProcess process2;
  process1.setStandardOutputProcess(&process2);
  process1.start("command1");
  process2.start("command2");
相关推荐
云和数据.ChenGuang6 小时前
Python 常见特殊方法详解:__new__、__init__、__del__、__str__、__repr__ 与 __getattribute__
开发语言·人工智能·python·1024程序员节
海宇服务6 小时前
零信任架构实战:基于海宇全国车辆配置查验构建自动化二手商用车出厂参数建档网关
运维·人工智能·架构·自动化·1024程序员节
GeW8 小时前
新质生产力路线图落地,Linux运维与数据库架构师的机会清单
linux
zhippt_10148 小时前
AI生成PPT工具推荐:图转PPT与一键生成实测对比
人工智能·1024程序员节
Brilliantwxx8 小时前
【Linux】 文件访问与路径解析:目录、文件名、dentry、路径缓冲与 dcache 全解析
linux·运维·服务器·开发语言·spring
鬼手点金8 小时前
KV Cache 未必是一次性的:可编辑、可组合的“笔记”
java·人工智能·笔记·学习·自动化·1024程序员节
深圳光特通信豆子8 小时前
使用光特通信光模块构建核心-分布-接入三层园区网络
1024程序员节
father_12278 小时前
Greenplum 集群故障恢复与主备同步机制实战
linux·网络·greenplum
ynchyong9 小时前
linux中的 sed` 与 `seq`
linux·运维·sed·seq·文本工具
喜欢猪猪9 小时前
把记忆搬出显存:DeepSeek-V4.1-Flash Engram 与“第二稀疏轴“的架构革命
1024程序员节