QProcess Class cannot get the output content when executing shell script?
-
proc2.start("./a.sh");
proc2.waitForFinished();
qDebug() << proc2.readAll();The a.sh file is placed in the build directory. The command ./a.sh can run normally under the build directory when I use terminal.
The content of the a.sh file is "ps -ef|grep xterm"At the beginning, I used the following code to execute the shell command directly. When I found that there was no output, I used the above method to run a shell script. How can I do that
proc2.start("ps -ef|grep xterm") ;
proc2.waitForFinished();
qDebug() << proc2.readAll(); -
@eyllanesc said in QProcess Class cannot get the output content when executing shell script?:
/bin/sh
It works. Thank you.
May I ask why this code doesn't work?
proc2.start("ps -ef|grep xterm") ;
proc2.waitForFinished();
qDebug() << proc2.readAll(); -
@jiaming said in QProcess Class cannot get the output content when executing shell script?:
May I ask why this code doesn't work
two separate issues:
first insance of calling a shell script --
It has to do with the child process environment. the PATH is only aware of the system default when the child shell starts.second instance of calling a piped command --
pipes are a shell function and you call ps directly so the child process isn't running under a shell that can interpret the pipe. -
@jiaming
You do not say which version of Qt you are using. The solution you have picked uses overloadQProcess::start(const QString &commandline)
. That overload has been removed in recent versions of Qt 5, e.g. it is not present in latest Qt 5.15, it will not work going forward.I recommend you change over to the supported void QProcess::start(const QString &program, const QStringList &arguments, QIODevice::OpenMode mode = ReadWrite).
proc2.start("/bin/sh", QStringList() << "-c" << "ps -ef | grep xterm");
Having said that. You are going to be reading the output from this command from stdout (else there would be no point in executing it). By the time you read the lines coming in you could simply look in them for the desired
xterm
string via your own code, saving the need to use/bin/sh
, a pipe and runninggrep
, i.e. justproc2.start("ps", QStringList() << "-ef");
Up to you.
P.S.
If you really don't want to look through the output forxterm
in your own code, then if yourps
takes a-C
argument (e.g. Ubuntu does) you should find that the following command, without/bin/sh
, pipe orgrep
, does the job (and does not pick up presumably-unintended matches on the stringxterm
):proc2.start("ps", QStringList() << "-C" << "xterm");
-
@jiaming said in QProcess Class cannot get the output content when executing shell script?:
Is there any better suggestion?
Of course! I only put that in as a "P.S." if it gave what you wanted. I already showed you two other examples (both using
-ef
) of what to use if notps -C
.... And told you what you presently have may work in Qt 5.12 but will not if/when you move to a later Qt version.