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

99封情书 提交于 2019-12-22 11:15:56

问题


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 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?


回答1:


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.




回答2:


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 .




回答3:


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

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




回答4:


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);
}


来源:https://stackoverflow.com/questions/7597062/qprocess-messes-my-linux-command-up-i-think-how-to-fix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!