开发者

Qprocess messes my linux command up (i think). how to fix? [duplicate]

开发者 https://www.devze.com 2023-04-09 02:00 出处:网络
This question already has answers here: Command working in terminal, but not via QProcess (3 answers) Closed 9 years ago.
This question already has answers here: Command working in terminal, but not via QProcess (3 answers) Closed 9 years ago.

I need to force my c++ QT4 application to read results from a linux command. I am trying to use Qprocess but as soon as my command gets complicated it get messed somehow (just guessing) and does not work.

Here i try to make for yu a small example:

QProcess process;
command = "ls -l | grep a | sort";
qDebug() << "Execute command -> "+command;
process.start( command );
process.waitForFinished(-1);
QString processStdout = process.readAllStandardOutput();
QString processStderr = process.readAllStandardError();
qDebug() << "Std out -> "+processStdout;
qDebug() << "Std开发者_JAVA百科 err -> "+processStderr;

this will print:

Execute command -> ls -l | grep a | sort
"Std out -> " 
"Std err -> ls: |: No such file or directory

while would correctly print the file names if runed from the consol.

If i replace the comman with somethink simpler such command = "ls -l"; it work smoothless The error is returned on standar error by the OS.

I guess thereforethat the Qstring used for the command gets manipolated somehow. Any idea about wht's happening?


QProcess does not support shell commands. The pipe symbols is thus not interpreted by a shell, but instead directly passed to ls. ls interprets it as file name, and complains because apparantly there is no file named |.

You need to setup pipes manually by redirecting input and output streams of QProcess objects. Read the documentation to learn how to do this.

Generally how should avoid shell commands, and instead rely on Qt classes and functions. There is certainly no need to call grep or ls, because the same can be done easier with QRegExp, and QDir. If you need to execute subprocesses, then use the ::start(const QString&, const QStringList&, OpenMode) overload and pass all arguments as list to avoid quoting issues.


Try this :

Run shell from QProcess and pass arguments to shell. Example :

QStringList options;
options << "-c" << "ls -l | grep a | sort";
QProcess process;
process.start("/bin/sh", options); //Use sh or another shell 

Let me know is this worked or not .


command = "ls -l | grep a | sort";

isn't actually a process but pipeline of 3 different processes: ls, grep and sort.


thanks all guys for the help.

in order to do what i needed i had to change the aproach using:

std::string cmd("/sbin/ifconfig eth0");
FILE* pfd = popen(cmd.c_str(), "r");

if (pfd)
{
  while (!feof(pfd))
  {
    char buf[1024] = {0};

    if (fgets(buf, sizeof(buf), pfd) > 0)
    {
      std::cout << "buf = " << buf;    // a newline is already present
    }
  }
  pclose(pfd);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号