Why originated process started as zombie in Qt-app. Linux - c++

I am writing a small application on linux using qt creator.
When i start my application i want it to execute a shell command. I`m using QProcess for it like this:
int main(int argc, char *argv[])
{
MyApplication a(argc, argv);
QProcess mapProc(&a);
QString command;
QStringList args;
command = "java";
args << "-jar" << "/home/$USER/MapServer/map.jar" << "localhost" << "9797" << "12123";
mapProc.start(command, args);
bool flag = mapProc.waitForStarted();
QProcess::ProcessState state = mapProc.state();
qDebug() << mapProc.errorString();
qDebug() << mapProc.pid();
/*/////////////////
some code
/////////////////*/
return a.exec();
}
but when my application started, process "mapProc" becomes a zombie. Why? what am i doing wrong?

$USER will not really work like that with QProcess. You will need to invoke the command through /bin/sh -c "mycmd" or even better if you just do it the proper Qt way as indicated below.
Try using QStandardPaths, so write this:
QString homeLocation =
QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
args << "-jar" << QString(homeLocation.first() + "/MapServer/map.jar")
<< "localhost" << "9797" << "12123";
instead of this:
args << "-jar" << "/home/$USER/MapServer/map.jar"
<< "localhost" << "9797" << "12123";

Related

How to run command line with QProcess?

i have a application (X)Medcon, i want to run command line (convert file) with QProcess. I tried but it is not success. This is my code
convertDicomProcess = new QProcess(this);
QString program = "C:\\Program Files\\XMedCon\\bin\\xmedcon.exe";
QStringList arguments;
arguments << "medcon"<< "-f" << "F:/33.nii" << "-c" << "dicom" << "-o" << "F:/33.dcm";
convertDicomProcess->start(program, arguments);
convertDicomProcess->waitForFinished();
QByteArray output = convertDicomProcess->readAll();
convertDicomProcess->close();
When i run command line with
medcon -f E:\55.nii -c dicom -o
E:\55.dcm
it is convert success
Try:
QStringList arguments;
arguments << "/c" << program << "-f" << "F:/33.nii" << "-c" << "dicom" << "-o" << "F:/33.dcm";
convertDicomProcess->start("cmd.exe", arguments);
Test if you really need "medcon" as an argument again, I do not know since I do not know the "medcon" program. If yes change it to:
arguments << "/c" << program << "medcon" << "-f" << "F:/33.nii" << "-c" << "dicom" << "-o" << "F:/33.dcm";
This code tries to run the medcon program in a shell.
If you path exists, I think you need to use quotes (\") in the string for the one:
QString program = "\"C:\\Program Files\\XMedCon\\bin\\xmedcon.exe\"";
...

reading and writing to QProcess in Qt Console Application

Noted: this appears to be a specific issue question but hopefully it can be edited for all to related to
I need to interact with a QProcess object.
The Problem:
I am not getting any output from QProcess after calling QProcess:write(input)
More Info:
Going through the doc pages led me to create an example below:
I have a script requesting user input, and finally displaying and appropriate message based on the user input.
Testing:
After adding a "log" feature to my script for testing, the following occurs:
script executes
script requests user input (confirmed by the 'first' qDebug() << p->readAll())
script accepts input from QProcess (confirmed by script 'log output')
After this, no output is received. The following 2 debug statements both fire (i.e. wait 30s each)
if (!p->waitForReadyRead()) {
qDebug() << "waitForReadyRead() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
if (!p->waitForFinished()) {
qDebug() << "waitForFinished() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
Followed by:
QString s = QString(p->readAll() + p->readAllStandardOutput());
where s is an empty string.
The issue is s should contain either "success" or "failed"
Calling Code:
QString cmd = QString("sh -c \"/path/to/bashscript.sh\"");
QString input = QString("Name");
QString result = runCommand(cmd, input)
Process Code:
//takes 2 parameters,
// cmd which is the code to be executed by the shell
// input which acts as the user input
QString runCommand(QString cmd, QString input){
QProcess *p = new QProcess(new QObject());
p->setProcessChannelMode(QProcess::MergedChannels); //no actual reason to do this
p->start(cmd);
if (p->waitForStarted()) {
if (!p->waitForReadyRead()) {
qDebug() << "waitForReadyRead() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
if (!p->waitForFinished()) {
//reads current stdout, this will show the input request from the bash script
//e.g. please enter your name:
qDebug() << p->readAll();
//here I write the input (the name) to the process, which is received by the script
p->write(ps.toLatin1());
//the script should then display a message i.e. ("success" o "failed")
if (!p->waitForReadyRead()) {
qDebug() << "waitForReadyRead() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
if (!p->waitForFinished()) {
qDebug() << "waitForFinished() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
}
QString s = QString(p->readAll() + p->readAllStandardOutput());
return s;
}
else{
qDebug() << "waitForStarted() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
p->waitForFinished();
p->kill();
return QString();
}
script.sh (-rwxrwxr-x)
#!/bin/bash
#returns
# "success" on non empty $n value
# "failed: on empty $n value
#
echo "enter your name:"
read n
if [[ ! -z $n ]];
then
echo "success"
exit 0;
else
echo "failed"
exit 1;
fi
UPDATE
#KevinKrammer I modified the run command as you said, also using the QStringList with the args.
Still does not get output, infact the waitForReadyRead() and waitForFinished() returns false instantly.
Called with:
QString r = runCommand(QString("text"));
Process Code:
QString runCommand(QString input){
QProcess *p = new QProcess(new QObject());
p->setProcessChannelMode(QProcess::MergedChannels);
//script is the same script refered to earlier, and the `cd /home/dev` IS required
p->start("sh", QStringList() << "-c" << "cd /home/dev" << "./script");
;
if (p->waitForStarted()) {
if (!p->waitForReadyRead(5000)) {
qDebug() << "waitForReadyRead() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
qDebug() << p->readAll();
p->write(input.toLatin1());
if(!p->waitForFinished(5000)){
qDebug() << "waitForFinished() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
QString s = QString(p->readAll() + p->readAllStandardOutput());
return s;
}
else{
qDebug() << "waitForStarted() [false] : CODE: " << QVariant(p->error()).toString() << " | ERROR STRING: " << p->errorString();
}
p->waitForFinished();
p->kill();
return QString();
}
Terminal Output of the Process:
started
readChannelFinished
exit code = "0"
waitForReadyRead() [false] : CODE: "5" | ERROR STRING: "Unknown error"
""
waitForFinished() [false] : CODE: "5" | ERROR STRING: "Unknown error"
Press <RETURN> to close this window...
Thoughts on this?
UPDATE 2
#Tarod Thank you for taking the time to make a solution.
It works, however not completely is expected.
I copied over your code, exactly.
Made a few changes in the mReadyReadStandardOutput()
See additional info below.
The problem:
After running the application (and script), I get a result -> AWESOME
Everytime it is the incorrect result i.e. "failed". -> NOT AWESOME
Terminal Output:
void MyProcess::myReadyRead()
void MyProcess::myReadyReadStandardOutput()
"enter your name:\n"
""
void MyProcess::myReadyRead()
void MyProcess::myReadyReadStandardOutput()
"failed\n"
Press <RETURN> to close this window...
script contents:
#!/bin/bash
echo "enter your name:"
read n
echo $n > "/tmp/log_test.txt"
if [[ ! -z "$n" ]];
then
echo "success"
exit 0;
else
echo "failed"
exit 1;
fi
/tmp/log_test.txt output
myname
running this manually from console:
dev#dev-W55xEU:~$ ls -la script
-rwxrwxr-x 1 dev dev 155 Jan 25 14:53 script*
dev#dev-W55xEU:~$ ./script
enter your name:
TEST_NAME
success
dev#dev-W55xEU:~$ cat /tmp/log_test.txt
TEST_NAME
Full code:
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
class MyProcess : public QProcess
{
Q_OBJECT
public:
MyProcess(QObject *parent = 0);
~MyProcess() {}
public slots:
void myReadyRead();
void myReadyReadStandardOutput();
};
MyProcess::MyProcess(QObject *parent)
{
connect(this,SIGNAL(readyRead()),
this,SLOT(myReadyRead()));
connect(this,SIGNAL(readyReadStandardOutput()),
this,SLOT(myReadyReadStandardOutput()));
}
void MyProcess::myReadyRead() {
qDebug() << Q_FUNC_INFO;
}
void MyProcess::myReadyReadStandardOutput() {
qDebug() << Q_FUNC_INFO;
// Note we need to add \n (it's like pressing enter key)
QString s = this->readAllStandardOutput();
qDebug() << s;
if (s.contains("enter your name")) {
this->write(QString("myname" + QString("\n")).toLatin1());
qDebug() << this->readAllStandardOutput();
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyProcess *myProcess = new MyProcess();
QString program = "/home/dev/script";
myProcess->start("/bin/sh", QStringList() << program);
a.exec();
}
#include "main.moc"
script issue? QProcess issue?
Unfortunately I don't have all your code, so I made an example. I hope it helps you.
If I compare my code to yours, I think the problem could be you are not calling readAllStandardOutput() after writing or maybe you are not calling exec() in your main.cpp.
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
class MyProcess : public QProcess
{
Q_OBJECT
public:
MyProcess(QObject *parent = 0);
~MyProcess() {}
public slots:
void myReadyRead();
void myReadyReadStandardOutput();
};
MyProcess::MyProcess(QObject *parent)
{
connect(this,SIGNAL(readyRead()),
this,SLOT(myReadyRead()));
connect(this,SIGNAL(readyReadStandardOutput()),
this,SLOT(myReadyReadStandardOutput()));
}
void MyProcess::myReadyRead() {
qDebug() << Q_FUNC_INFO;
}
void MyProcess::myReadyReadStandardOutput() {
qDebug() << Q_FUNC_INFO;
// Note we need to add \n (it's like pressing enter key)
this->write(QString("myname" + QString("\n")).toLatin1());
// Next line no required
// qDebug() << this->readAll();
qDebug() << this->readAllStandardOutput();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyProcess *myProcess = new MyProcess();
QString program = "/home/fran/code/myscript.sh";
myProcess->start("/bin/sh", QStringList() << program);
a.exec();
}
#include "main.moc"
Script to test the application:
echo "enter your name:"
read n
if [ ! -z "$n" ];
then
echo "success"
exit 0;
else
echo "failed"
exit 1;
fi

Using std::cout in Qt Gui

I have an application that when run through terminal, the user has the option between command-line mode or GUI mode.
There doesn't seem to be any output to the console at all when using std::cout. std::cout statements don't work in the main event loop.
I have added CONFIG += console to my .pro file.
For now, I have been using QTextStream() which works fine:
QTextStream(cout) << "Hello World" << std::endl;
My question is:
Why can I not use std::cout? Does this have something to do with Qt affecting input and output streams? I couldn't find any documentation in Qt's docs on this.
int main(int argc, char *argv[])
{
std::cout << argv[1] << std::endl; //This is being outputted.
//if(argc == 2 && !strcmp(argv[1],"-win")){
if(true){ //Just for this example's sake
QApplication a(argc, argv);
std::cout << "Hello" << std::endl; //This is not being ouputted.
MainWindow w;
w.show();
return a.exec();
}
else
{
qDebug() << "Console Mode.\n";
std::cout << "Console Mode.\n";
//Do stuff
}
}
This is not a Qt issue, but how std::cout works. You seem to blow up your std::cout in here:
std::cout << argv[1] << std::endl;
Your issue can be reproduced even with a simple program like this:
main.pro
TEMPLATE = app
TARGET = main
CONFIG -= qt
SOURCES += main.cpp
main.cpp
#include <iostream>
int main(int /*argc*/, char **argv)
{
std::cout << argv[1] << std::endl;
std::cout << "Hello stdout!" << std::endl;
if (std::cout.bad())
std::cerr << "I/O error while reading\n";
return 0;
}
Build and Run
Success: qmake && make && ./main foo
Failure: qmake && make && ./main
In your case argv[1] is nil and so this makes std::cout not to print anything more. I would suggest to either pass an argument all the time and/or check against argc with some help usage print. The best would be to use the builtin command line parser in QtCore these days.
You could ask why? Because it is undefined behavior. You can read the details from the documentation:
basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb);
After constructing and checking the sentry object, checks if sb is a null pointer. If it is, executes setstate(badbit) and exits.
If you happen to have an issue with the IDE itself, for instance QtCreator, then follow these steps in case of QtCreator:
Projects -> Select a kit -> Run tab -> Run section -> Arguments
Works OK for me:
QT += core
QT -= gui
TARGET = untitled
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
main.cpp:
#include <QCoreApplication>
#include <QTextStream>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::cout << "Hello World" << std::endl;
return a.exec();
}
EDIT:
#include <QCoreApplication>
#include <QTextStream>
#include <QtWidgets/QWidget>
#include <QDebug>
#include <iostream>
int main(int argc, char *argv[]) {
std::cout << "test" << std::endl; // <--- THE PROBLEM IS HERE...IF YOU TRY A SIMPLE STRING IT WORKS FINE SO THE PROBLEM IS argv[1] IS AN EMPTY STRING
//if(argc == 2 && !strcmp(argv[1],"-win")){
if(true){
//Just for this example's sake
QCoreApplication a(argc, argv);
std::cout << "Hello" << std::endl; //This is not being ouputted.
return a.exec();
}
else
{
qDebug() << "Console Mode.\n";
std::cout << "Console Mode.\n";
//Do stuff
} }

QSerialPort::readLine doesn't work as expected on MS Windows

I'm trying to connect a micro-controller with my desktop PC via USB-serial cable.
The OS of my desktop PC is Windows 8.1, and USB-serial cable is TTL-232R-3V3. (FTDI)
(Qt version: 5.2.0 beta1, QtCreator Version: 3.0, Compiler: MSVC2012)
Now I'm trying read/write loop-back tests, and that's why RX/TX pin of USB-serial cable are connected with each other.
Here is my code.
#include <QtCore/QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QtCore/QDebug>
#define PORT_NAME "COM3"
#define BAUDRATE 19600
#define TIMEOUT_MS 1000
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSerialPort pSerial(PORT_NAME);
const char strMsg[] = "#1:Send data line \n #2:Send data line\n #3:Send data line end\n";
char strBuf[256];
qint64 nByte;
if(pSerial.open(QIODevice::ReadWrite)){
pSerial.setBaudRate(BAUDRATE);
qDebug() << "OPEN PASS";
pSerial.write(strMsg);
pSerial.flush();
if(pSerial.waitForBytesWritten(TIMEOUT_MS)){
qDebug() << "WRITE PASS";
}
pSerial.waitForReadyRead(TIMEOUT_MS);
while(true){
if( pSerial.canReadLine()){
qDebug() << "CAN READ LINE";
nByte = pSerial.readLine(strBuf,sizeof(strBuf));
qDebug() << "Length: " << nByte;
qDebug() << "Read data: " << strBuf;
}
}
pSerial.close();
} else {
qDebug() << "OPEN FAIL\n";
}
return a.exec();
}
When the program starts to run, the result is different than I expected.
Only first line of sent data can be received. So, "Read data: #1 Send data line" is printed
on console. But the rest of sent data will never be received. Does anyone know why?
Any help would be appreciated.
Thanks in advance.
EDIT: I revised my code according to Papp's comment.Then it works as I expected.
All sent message has been received.
Does it mean I misunderstand the usage about readLine() or canReadLine()?
// while(true){
// if( pSerial.canReadLine()){
// qDebug() << "CAN READ LINE";
// nByte = pSerial.readLine(strBuf,sizeof(strBuf));
// qDebug() << "Length: " << nByte;
// qDebug() << "Read data: " << strBuf;
// }
// }
pSerial.waitForReadyRead(TIMEOUT_MS);
QByteArray readData = pSerial.readAll();
while (pSerial.waitForReadyRead(TIMEOUT_MS)) {
readData.append(pSerial.readAll());
}
qDebug() << "Read data: " << readData;
EDIT 2nd time : Following code also works for me.
while(true){
if( pSerial.waitForReadyRead(TIMEOUT_MS) && pSerial.canReadLine()){ // I revised this line
qDebug() << "CAN READ LINE";
nByte = pSerial.readLine(strBuf,sizeof(strBuf));
qDebug() << "Length: " << nByte;
qDebug() << "Read data: " << strBuf;
qDebug() << "Error Message: " << pSerial.errorString();
}
}
That is because you need to read in a loop like this:
QByteArray readData = serialPort.readAll();
while (serialPort.waitForReadyRead(5000))
readData.append(serialPort.readAll());
Please see the creadersync example for the details what I added to 5.2. You can also check the creaderasync example for non-blocking operation.
To be fair, we have not tested readLine that much, but it works for me on Unix, so does it on Windows for someone else.
The mistake that you've made is expecting to receive all the sent data when waitForReadyRead returns. When waitForReadyRead finishes, all you're guaranteed is some data being available to be read. It may be as little as one character, not necessarily a whole line.
The loop from your last modification is the almost correct way to do it. You should nest reading of the lines in a separate loop. The following code is how it should be done, and agrees with the semantics of QIODevice:
while (pSerial.waitForReadyRead(TIMEOUT_MS)) {
while (pSerial.canReadLine()) {
qDebug() << "NEW LINE";
QByteArray line = pSerial.readLine();
qDebug() << "Length: " << line.size();
qDebug() << "Read data: " << line;
qDebug() << "Error Message: " << pSerial.errorString();
}
}
qDebug << "TIMED OUT";
Note that none of this code should even run in the GUI thread. Ideally you should move it to a QObject, use the signals emitted by QIODevice (and thus QSerialPort), and move that object to a separate thread.
The GUI thread can sometimes block for long periods of time, it's not normally desirable to have it disturb the timeliness of your device communication. Similarly, you don't want device timeouts to block the GUI thread. Both are equally bad and are a very common source of bad user experience. Qt makes multithreading very easy - leverage it for your user's sake, and do it properly.
On Linux I have to do it this way to receive ASCII text ending with '\n'
QByteArray readData = pSerial.readAll();
while (readData[readData.length() - 1] != '\n') {
pSerial.waitForReadyRead(5000);
readData.append(pSerial.readAll());
}
QString result(readData);
QSerialPort::readLine() doesn't work for me either

Supplying parameters to a Linux binary while running it from QtProcess

The standard way to use Qprocess is as follows:
QObject *parent;
...
QString program = "./path/to/Qt/examples/widgets/analogclock";
QStringList arguments;
arguments << "-style" << "motif";
QProcess *myProcess = new QProcess(parent);
myProcess->start(program, arguments);
However, What I am trying to do is running the binary on the console (sh) and then copying the output from there to the textbox in Qt.
So now what I need to do in myProcess->start(program, arguments); is to pass sh in program and the binary name in arguments. But what if my binary takes commandline arguments too ? Where do i supply it ?
You can use arguments() :
#include <QApplication>
...
QStringList myArgs = qApp->arguments();
myProcess->start(program, myArgs);
I tried this:
/home/user/1.sh
#!/bin/sh
echo $1 >> /home/user/1.out
echo $2 >> /home/user/1.out
echo $3 >> /home/user/1.out
main.cpp
#include <QtCore>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString program = "sh";
QStringList args;
args << "/home/user/1.sh" << "qwe" << "123" << "c c c";
QProcess p;
p.start(program, args);
p.waitForFinished();
return 0;
}
After running my app, I got:
1.out
qwe
123
c c c
Seems working for me.