PDA

View Full Version : running shell command from C++ code problem



alex chpenst
30th July 2008, 14:42
Hi,

My program needs to get a list of users on the system. From linux shell it works fine:
# who | cut -d' ' -f1 | sort -u

When I start this from code I get an error with exit code 255. I've read that this means that some libraries can't be found. What libraries are necessary and how and where to declare them for C++ program? Are these libraries for who, cut and sort commands?



QProcess exec;
exec.start( "who|cut -d' ' -f1|sort -u" );
exec.waitForFinished();
int exitcode = exec.exitCode(); // exitcode is always 255!

Thanks!!

jpn
30th July 2008, 14:59
You need a shell to interpret the command. See for example this post (http://www.qtcentre.org/forum/p-qprocess-and-spumux-post57472/postcount2.html).

alex chpenst
30th July 2008, 15:22
This works fine, thanks a million!!


QStringList arguments;
arguments << "-c" << "who|cut -d' ' -f1|sort -u";
QProcess exec;
exec.start("/bin/sh", arguments);

SunnySan
30th July 2008, 16:12
How could we adjust this code to windows command?
should we replace /bin/sh with win32 or something?

thanks
SunnySan

bst
31st July 2008, 10:41
Hi,

use cmd.exe with /c


QStringList arguments;
arguments << "/c dir /b e:\\test\\*.txt | sort";
QProcess exec;
exec.start("cmd.exe", arguments);
exec.waitForFinished();
qDebug() << exec.readAllStandardOutput();

HTH, Bernd