加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用C中的QProcess重定向gnome-terminal的输出

发布时间:2020-12-16 07:34:04 所属栏目:百科 来源:网络整理
导读:我正在尝试为gui生成一个子进程,它将生成一个终端.我希望此终端(stdout和stderr)生成的数据显示在出现的窗口以及设置的日志文件中.当我直接在 shell中输入命令时,它按预期工作,但当作为启动命令提供给QProcess时,它实际上不会向文件写入任何内容. 例如:如果
我正在尝试为gui生成一个子进程,它将生成一个终端.我希望此终端(stdout和stderr)生成的数据显示在出现的窗口以及设置的日志文件中.当我直接在 shell中输入命令时,它按预期工作,但当作为启动命令提供给QProcess时,它实际上不会向文件写入任何内容.

例如:如果用户没有安装二进制文件,则应该写入bin.log,找不到该命令.我已经为生成的QProcess设置了我的环境,使其与正在运行的父进程相同(以便它可以找到bash和其他任何东西),并在调用QProcess.start()方法之前设置了工作目录.我写了一个测试用例如下:

gnome-terminal --title 'Sub-Terminal' -e 'bash -c "foo [args to foo] |& tee foo.log"'

在Qt中,我执行以下操作:

QProcess *child = new QProcess(this);
QString   cmd   = "gnome-terminal --title 'Sub-Terminal' -e 'bash -c "foo [args to foo] |& tee foo.log"'";
child->setProcessEnvironment(<process environment I have created before>);
child->setWorkingDirectory(<current working dir>);
child->start(cmd);
...

它生成终端但不向foo.log写入任何数据.我也尝试过以下方法:

QProcess *child = new QProcess(this);
QString   prog  = "gnome-terminal"
QStringList args;
args << "-x" << "bash" << "foo" << "[foo's arguments]" << "|&" << "tee" << "foo.log";
// set the process env and working dir
child->start(prog,args);

有没有人对如何解决这个问题有任何建议?
我已经尝试使用QProcess.setStandardErrorFile(foo.log)和QProcess.setStandardOutputFile(foo.log)重定向stdout和stderr,但似乎这将从gnome-terminal本身重定向stdout(这不是任何东西).

解决方法

你必须在终端中提供要在终端中执行的整个命令作为“-e”之后QProcess的单个参数,以及将bash中执行的命令作为bash的单个参数:

args << "-e" << "bash -c 'foo [args to foo] |& tee foo.log'";

这基本上执行

bash -c 'foo [args to foo] |& tee foo.log'

在终端中,它本身执行

foo [args to foo] |& tee foo.log

在bash中.

您的猜测是正确的,读取gnome-terminal进程的输出不起作用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读