Calling execv inside a QProcess triggers finished() signal under Windows only - c++

I wrote this example to illustrate a difference between linux and windows on process handling.
My main application starts a sub-app by calling QProcess::start(). If this sub-process restarts itself by calling execv (_execv under Windows), the finished() signal is triggered on the top application only under Windows. In my case, this is unexpected.
Is there a way to avoid this signal, or this is a QProcess bug?
Mathieu
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect( ui->pushButtonStart, SIGNAL( clicked() ), this, SLOT( start() ) ) ;
connect( ui->pushButtonRestart, SIGNAL( clicked() ), this, SLOT( restart() ) ) ;
connect( &m_process, SIGNAL( finished(int, QProcess::ExitStatus) ),
this, SLOT( finished(int, QProcess::ExitStatus) ) ) ;
m_process.setProcessChannelMode( QProcess::MergedChannels );
}
MainWindow::~MainWindow()
{
delete ui;
}
void
MainWindow::start()
{
m_process.start( qPrintable( QApplication::applicationFilePath() ) ) ;
}
void
MainWindow::restart()
{
char *argv[2] ;
argv[0] = strdup( QApplication::applicationFilePath().toStdString().c_str() ) ;
argv[1] = NULL ;
execv( qPrintable( QApplication::applicationFilePath() ), argv ) ;
}
void
MainWindow::finished
(
int exitCode,
QProcess::ExitStatus exitStatus
)
{
qDebug() << "Finished!" ;
}

Related

client program crashes when connect to server after disconnect Qt

I am implementing client side of TCP-Ip server based on Qt but the program crashes when I closed connection and start again by hitting connect button.
Overview of project. I have Qwidget ( main application) with 2 lineEdit for user to input port number and server Ip address.
It also has 2 button that connect to server and disconnect. On hitting connect button , it will call constructor of client socket and call connectToHost.
Testing: Tried testing on same computer with server running on port 6000 and ip address 127.0.0.1.
Problem: When I launch Client application.And input port number and address and hit connect button it connects successfully. And I can write to server successfully. then I click disconnect button and it disconnects successfully but after that if I connect again by clicking connect button it crashes. I know problem is with tcpSocket but have no idea how to fix it.
clientAgent( QWidget appilciation ).h
namespace Ui {
class ClientAgent;
}
class ClientAgent : public QWidget
{
Q_OBJECT
public:
explicit ClientAgent(QWidget *parent = 0);
~ClientAgent();
private:
Ui::ClientAgent *ui;
ClientForTest *tcpSockForTest;
// Qwidget declartion
below
....
private slots:
void startClient();
void stopClient();
public slots:
void getCliReqTextChanged();
};
ClientAgent.cpp
ClientAgent::ClientAgent( QWidget *parent ) :
QWidget(parent),
ui( new Ui::ClientAgent )
{
// Widget declartion and initilisation
// Layout design etc
//define signals and slots for Client
// signals and slots
connect( btnStartClient, SIGNAL( clicked() ), this, SLOT( startClient() ) );
connect( btnStopClient, SIGNAL( clicked() ), this, SLOT( stopClient() ) );
// for write
connect( lEditCliReq, SIGNAL( textChanged(const QString& ) ), this, SLOT( getCliReqTextChanged() ) );
ui->setupUi( this );
}
ClientAgent::~ClientAgent()
{
delete ui;
}
void ClientAgent::startClient()
{
qDebug() << " we are in strt Clinet";
qDebug() << " connecting ";
// get server address and port number from GUI
QString testAddr = lEditAddr->text();
QString testPort = lEditPrt->text();
tcpSockForTest = new ClientForTest( testAddr, testPort.toInt(), this );
if( tcpSockForTest->connectToServer() == true )
{
lblCliStatus->setText(" connected ....");
}
else
{
lblCliStatus->setText(" failed to connect....");
}
}
void ClientAgent::stopClient()
{
qDebug() << " disconnecting ";
tcpSockForTest->disconnectToServer();
delete tcpSockForTest;
}
ClientForTest.h
class ClientForTest : public QObject
{
Q_OBJECT
public:
ClientForTest( QString hostAddr, quint16 portNum, QObject *parent );
bool connectToServer();
void disconnectToServer();
QString getStoreMsgFrmCliReq( ) const;
void writeToTest(const QString& stripCmd );
void executeSignals();
~ClientForTest();
signals:
void sigSendData();
public slots:
void connectedToTest();
void connectionClosedByServer();
void error();
private:
QTcpSocket *sockFortest;
QString hostName;
quint16 portNumber;
quint16 nextBlockSize;
QString storeLineEditMsg;// store message from lineEditCliReq;
};
ClientForTest.cpp
ClientForTest::ClientForTest( QString hostAddr, quint16 portNum, QObject *parent ) :
hostName( hostAddr ),
portNumber( portNum ),
QObject( parent )
{
connect( sockFortest, SIGNAL( connected() ), this, SLOT( connectedToTest() ) );
connect( sockFortest, SIGNAL( disconnected() ), this, SLOT( connectionClosedByServer() ) );
connect( sockFortest, SIGNAL( error( QAbstractSocket::SocketError ) ), this, SLOT( error() ) );
storeLineEditMsg = "";
}
void ClientForTest::executeSignals()
{
// actually I need toplace itin constructor will do later on
connect( this, SIGNAL( sigSendData() ), this, SLOT( connectedToTest() ) );
}
ClientForTest::~ClientForTest()
{
sockFortest->close();
delete sockFortest;
}
bool ClientForTest::connectToServer()
{
sockFortest = new QTcpSocket( this->parent() ); // COULD be Probelm here but how to fix it?
sockFortest->connectToHost( hostName, portNumber );
nextBlockSize = 0;
executeSignals();
return sockFortest->waitForConnected(1000);
}
void ClientForTest::disconnectToServer()
{
sockFortest->close();
//sockFortest.close();
qDebug() << "in disconnect for Test ";
emit updateLabelinParent( updateStatusDis );
}
void ClientForTest::connectionClosedByServer()
{
qDebug() << "connection closed by server ";
if( nextBlockSize != 0xFFFF )
{
disconnectToServer();
}
}
void ClientForTest::error()
{
qDebug() << "in error ";
disconnectToServer();
}
void ClientForTest::writeToTest( const QString& stripCmd )
{
storeLineEditMsg = stripCmd;
if( sockFortest->state() == QTcpSocket::UnconnectedState )
{
sockFortest->close();
delete sockFortest;
sockFortest = new QTcpSocket( this->parent() );
if( connectToServer() == true )
{
qDebug() << " YEEEE CONNECTED AGAIN finally ";
}
}
if( sockFortest->state() == QTcpSocket::ConnectedState )
{
qDebug() << " YEEEE CONNECTED";
sigSendData();
}
}
void ClientForTest::connectedToTest( )
{
QByteArray block;
QDataStream out( &block, QIODevice::WriteOnly );
out.setVersion( QDataStream::Qt_4_3 );
QString stripCmd = getStoreMsgFrmCliReq(); // received info for some other function I havnt shown that func here
out << quint16( 0 ) << stripCmd;
out.device()->seek( 0 );
out << quint16( block.size() - sizeof( quint16 ) );
qDebug()<<" yeeeee connected state...";
sockFortest->write( block );
//reset storeLineEditMessage
storeLineEditMsg.clear();
}
A few things, that could all together be responsible for your crash:
you connect the signals inside the ClientForTest constructor, but the socket itself is created later. That won't work. Move the line sockFortest = new QTcpSocket(this); to the constructor, before connecting
Same line, use this instead of this->parent()
And finally: There are multiple places you create/delete the socket. Don't do it. Create the socket inside the constructor with this as parent, and that's it. In your connectToServer, establish the connection, and in disconnectToServer, close it using disconnectFromHost. Same goes for the startClient and stopClient. Create the object once and just use the connect/disconnect functions, no deleting.
If code is required, I can add some.
Since it was requested, here is some more explanation:
Of course you can use parent, but in your case, the ClientForTest is an QObject, too. If you set the ClientForTest as as parent of the socket and the widget as the parent of ClientForTest, they will be both cleaned up properly. If you use this->parent(), both will be destroyed "at the same time". However, one comes first and somtimes Qt changes the order, so your socket could be destroyed before the ClientForTest. The destructor of ClientForTest would crash. That won't happen if the socket is a child of the ClientForTest
The main difference between close() and disconnectFromHost() is that the first actually closes the OS socket, while the second does not. The problem is, after a socket was closed, you cannot use it to create a new connection. Thus, if you want to reuse the socket, use disconnectFromHost() otherwise close()
And regarding 3. and 4.:
What you are doing is creating the ClientForTest when the user clicks connect, and delete it as soon as he clicks disconnect. But thats no good design (IMHO). Since tcpSockForTest already is a member of the class, create it (via new) inside the constructor, and delete it in the destructor (optionally, because if you pass the widget as parent, Qt will delete it for you).

how to modify values of dynamically created Widget from different class QT/C++

I know this question has been asked few times but all suggestions given there doesn't work for me.
Overview: I am implementing client server model and wants that as soon as msg arrived in server it should get displayed in main Qt widget. the widget , I choose to display msg is QLineEdit.
I have 3 files in project at the moment. Agent_A which is has all widget created dynamically. Then Server_test based on QTCPServer and sockClient for socket connection. I have received message on sockclient successfully from client but I don't know how to display it correctly on Agent_A .
I have added function in socketClient.cpp to update function in Agent_A but I guess when creating instance it always being NULL.
First a small snippet of my code and then what I have tried. may be you guys can input some valuable info.
Agent_A.h
class Agent_A : public QWidget
{
Q_OBJECT
public:
explicit Agent_A(QWidget *parent = 0);
void setLineEdit( const& modifyStr ); // function to change lineEditCmdString
~Agent_A();
private:
Ui::Agent_A *ui;
QPushButton *buttonStartServer;
QPushButton *buttonStopServer;
// some other widgets
QLabel *labelDisplay;
QLineEdit *lineEditCmdString;// I want to modify this value from sock client
ServerTest *server;
// few slots defined here
}
Agent_A.cpp
Agent_A::Agent_A( QWidget *parent ):
QWidget( parent ),
ui( new Ui::Agent_A )
{
//define push buttons
buttonStartServer = new QPushButton( tr( "&Start Server" ) );
buttonStopServer = new QPushButton( tr( "S&top" ));
// some properties of other widgets defined here which is not relevant to mention here
labelDisplay = new QLabel( tr("DisplayMessgae" ) );
lineEditCmdString = new QLineEdit;// I want to modify this value on sock client
labelDisplay->setBuddy( lineEditCmdString );
// define signals and slots for Server
connect( buttonStartServer, SIGNAL( clicked() ), this, SLOT( startServers() ) );
connect( buttonStopServer, SIGNAL( clicked() ), this, SLOT( stopServer() ) );
// some layout here which agian is not important to mention here.
ui->setupUi( this );
}
Agent_A::~Agent_A()
{
delete ui;
}
void Agent_A::setLineEdit( const Qstring& modifyStr )
{
lineEditCmdString->setText( modifyStr );
}
// now by socket client which creates socket
sockClient.h
class SockClient : public QObject
{
Q_OBJECT
public:
explicit SockClient( QObject *parent, QTcpSocket* socket= 0 );
~SockClient();
// I have added this function to update QLIneEdit in Agent_A
void updateTextinParent(const QString &changeText);
signals:
private slots:
void readClient();
private:
// some other functions
QTcpSocket *socketClient;
quint16 nextBlockSize;
public slots:
};
sockclient.cpp
// constructor for sockclient and some other functions
SockClient::SockClient( QObject *parent, QTcpSocket* socket ) : QObject( parent )
{
socketClient = socket ;
// create signals and slots
connect( socketClient, SIGNAL( readyRead() ), this, SLOT( readClient() ) );
connect( socketClient, SIGNAL( disconnected() ), this, SLOT( deleteLater() ) );
}
SockClient::~SockClient()
{
socketClient->close();
delete socketClient;
}
void SockClient::readClient()
{
QDataStream clientReadStream( socketClient );
clientReadStream.setVersion( QDataStream::Qt_4_3 );
QString strRecvFrm;
quint8 requestType;
clientReadStream >> nextBlockSize;
clientReadStream >> requestType;
if( requestType == 'S')
{
clientReadStream >> strRecvFrm;
}
qDebug() << " the string is " << strRecvFrm; // Has recieved correctly from client
updateTextinParent( strRecvFrmMops ); // Now trying to update widget
socketClient->close();
}
void SockClient::updateTextinParent( const QString& changeText )
{
if( this->parent() == 0 )
{
qDebug() << " Parent not assigned"; // This get printed ..
}
Agent_A *agent = qobject_cast< Agent_A* >( this->parent() ); // ?? is this is right way to do..?
if( agent != NULL )
{
qDebug() << " we are in updateTextin" << changeText; // it never get printed so I assume instance is always nULL
agent->setLineEdit( changeText );
}
}
// ServerTest.cpp where instance of sockClient is created
ServerTest::ServerTest(QObject *parent) : QObject(parent)
{
server = new QTcpServer( this );
}
void ServerTest::startServer()
{
connect( server, SIGNAL( newConnection() ), this, SLOT( incomingConnection() ) );
if( !server->listen( QHostAddress::Any, 9999) )
{
qDebug() << " Server failed to get started";
}
else
{
qDebug() << " Server started";
}
}
void ServerTest::stopServer()
{
server->close();
qDebug() << "Server closed";
}
ServerTest::~ServerTest()
{
server->close();
delete socketforClient;
delete server;
}
void ServerTest::incomingConnection()
{
socketforClient = new SockClient(this->parent(), server->nextPendingConnection() );
}
This is a very simple example:
qt.pro:
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
HEADERS += classes.h
SOURCES += main.cpp
classes.h:
#include <QObject>
#include <QDebug>
class Agent_A : public QObject
{
Q_OBJECT
public slots:
void updateText(const QString &changeText) {
qDebug() << "updateText: " << changeText;
};
};
class SockClient : public QObject
{
Q_OBJECT
signals:
void updateTextinParent(const QString &text);
public:
void incomingText(const QString &text) {
emit updateTextinParent(text);
};
};
main.cpp:
#include "classes.h"
int main(int argc, char **argv) {
Agent_A *agent = new Agent_A;
SockClient client;
QObject::connect(&client, SIGNAL(updateTextinParent(const QString &)),
agent, SLOT(updateText(const QString &)));
client.incomingText(QString("hello"));
return 0;
}
Agent_A *agent = qobject_cast< Agent_A* >( this->parent() ); // ?? is this is right way to do..?
if( agent != NULL )
{
qDebug() << " we are in updateTextin" << changeText; // it never get printed so I assume instance is always nULL
agent->setLineEdit( chnageText );
}
Could you please check first that parent is not NULL?
And could you please show code where you create instance of SockClient?
Of course, you can't modify text because of you set as parent to socketClient object this pointer in Server_test class, so parent to socketClient will be Server_test but no Agent_A.
So make parent Agent_A for socketClient object:
socketforClient = new SockClient(this->parent(), server->nextPendingConnection());
Or you can make some others workarounds.
One more note: you make connection to newConnection() signal at your startServer method, not constructor. So if i start server, then stop them and start again server will be connected twice to signal and slot incomingConnection() will be called twice too. So you need disconnect at from signal at stopServer() method or do connection at constructor of class or use Qt::UniqueConnection.

Qt sending image between dialog

I'm writing a simple application with 2 dialogs, the first for one original image, which is sent to another dialog and processed. Then the image processed is sent back to the first dialog:
ImageDialog::ImageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ImageDialog)
{
ui->setupUi(this);
ui->graphicsView->setScene(&mScene);
mPixmapItem = new QGraphicsPixmapItem();
connect( this, SIGNAL( sigCommitImage(QImage) ),
parent, SLOT( updateImage(QImage) ) );
}
ImageDialog::~ImageDialog()
{
delete ui;
delete mPixmapItem;
}
void ImageDialog::processImage(const QImage &image )
{
cv::Mat tmp(image.height(),image.width(),CV_8UC4,(uchar*)image.bits(),image.bytesPerLine());
cv::cvtColor(tmp, tmp, CV_RGBA2GRAY);
mImage = QImage( (uchar*)tmp.data, tmp.cols, tmp.rows, tmp.step, QImage::Format_Indexed8 );
mPixmapItem->setPixmap(QPixmap::fromImage(mImage));
mScene.clear();
mScene.addPixmap(QPixmap::fromImage(mImage));
mScene.setSceneRect(0, 0, mImage.width(), mImage.height());
ui->graphicsView->fitInView(mPixmapItem, Qt::KeepAspectRatio);
}
void ImageDialog::on_buttonBox_accepted()
{
emit( sigCommitImage( mImage ) );
}
and there's a snippet for the main window
mPixelInfoDialog = new PixelInfoDialog( this );
connect( this, SIGNAL( sigPixelInfoDialog(QPixmap, QPointF) ),
mPixelInfoDialog, SLOT( updateClip(QPixmap, QPointF) ) );
mImageDialog = new ImageDialog( this );
connect( this, SIGNAL( sigImageDialog(QImage) ),
mImageDialog, SLOT( processImage(QImage) ) );
void MainWindow::updateImage(const QImage &image)
{
showImage( image );
}
void MainWindow::showImage(const QImage &image)
{
mImage = image;
mPixmapItem->setPixmap(QPixmap::fromImage(image));
mScene.clear();
mScene.addPixmap(QPixmap::fromImage(image));
mScene.setSceneRect(0, 0, image.width(), image.height());
ui->graphicsView->fitInView(mPixmapItem, Qt::KeepAspectRatio);
}
void MainWindow::on_action_Open_triggered()
{
QString path = QFileDialog::getOpenFileName();
if( path.isEmpty() )
{
return;
}
QImage image(path);
if( image.isNull() )
return;
showImage( image );
/*
* Update other open dialogs
*/
if( mImageDialog->isEnabled() )
{
emit( sigImageDialog( mImage ) );
}
}
The image is properly loaded, sent to ImageDialog and processed, but when I try to send back the image, the result is a bunch of random pixel or the application crash in
mPixmapItem->setPixmap(QPixmap::fromImage(image));
I can't figure what's happening because I'm doing the same operations.
Any advice?
Thanks in advance

No such slot message with QtPublish&Subscribe

My QValueSpaceSubscriber cannot find the public slot datachanged I created for some reason,
public slots: void datachanged();
suc = new QValueSpaceSubscriber ("/Allstar/external/", this);
QObject::connect(suc, SIGNAL( contentsChanged()),this,
SLOT( datachanged();) );
I always get this message:
[Qt Message] Object::connect: No such slot ExternalAccess::datachanged();
ExternalAccess::ExternalAccess(QObject *parent):
QObject(parent)
{
qDebug() << "Loading.......";
suc = new QValueSpaceSubscriber ("/Allstar/external/", this);
QObject::connect(suc, SIGNAL( contentsChanged()),this,
SLOT( datachanged();) );
qDebug() << suc->value("/url").toString();
}
void ExternalAccess::datachanged()
{
//stuff
}
I've ran a million cleans/builds ect but it still won't connect to the slot, does anyone know why it may be doing this?
You need to remove the ; inside the SLOT() call.
QObject::connect(suc, SIGNAL( contentsChanged()),this,
SLOT( datachanged();) );
should be
QObject::connect(suc, SIGNAL( contentsChanged()),this,
SLOT( datachanged()) );
Also make sure datachanged() is declared in ExternalAccess. The this in your connect call indicates to look in the current object.

Change QStackedLayout Index with QPushButton not QComboBox

I do this in Qt Creator. I want to change my QStackedLayout with only QPushButton, not QComboBox. Is this possible? Anybody has implemented this? I got many example from Qt Documentation but all examples use QComboBox (now QPushButton like I need). This is my code:
#mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
Dialog::Dialog()
{
QVBoxLayout *mainlayout = new QVBoxLayout;
QVBoxLayout *layouta = new QVBoxLayout;
QVBoxLayout *layoutb = new QVBoxLayout;
QPushButton *tombola = new QPushButton("A");
QPushButton *tombolb = new QPushButton("B");
QPushButton *tombolc = new QPushButton("C");
QFrame *framea = new QFrame;
QFrame *frameb = new QFrame;
QStackedLayout *stackia = new QStackedLayout;
layouta->addWidget(tombola);
layoutb->addWidget(tombolb);
framea->setLayout(layouta);
frameb->setLayout(layoutb);
framea->setMinimumSize(88,88);
frameb->setMinimumSize(88,88);
//building frame
framea->setFrameShape(QFrame::StyledPanel);
framea->setFrameShadow(QFrame::Raised);
frameb->setFrameShape(QFrame::StyledPanel);
frameb->setFrameShadow(QFrame::Raised);
//get c button smaller
tombolc->setMaximumWidth(33);
stackia->addWidget(framea);
stackia->addWidget(frameb);
stackia->addWidget(tombolc);
mainlayout->addLayout(stackia);
QPushButton *tombold = new QPushButton("D");
mainlayout->addWidget(tombold);
setLayout(mainlayout);
connect(tombold, SIGNAL(clicked()), stackia, SLOT(setCurrentIndex(1))); //CONNECTOR
}
RESULT
Qt Creator says:
Object::connect: No such slot QStackedLayout::setCurrentIndex(1)
What is my mistake?
At second chance after searching and asking for 4 days, I have changed my connect() and function code into:
CONNECTOR:
connect(tombold, SIGNAL(clicked()), stackia, SLOT(change_stack()));
FUNCTION:
void Dialog::change_stack()
{
stackia->setCurrentIndex(1);
}
RESULT
But Qt Creator says:
Object::connect: No such slot QStackedLayout::change_stack()
and immediately the window closed.
At my sight, my code has error. But I don't know what error so I can't change QStackLayout content/page into another page. What is my mistake? I believe this is actually quite simple but I just don't know where is the error.
Any suggestion?
You should add change_stack function to your Dialog class and connect to it like this:
class Dialog : public QWidget
{
...
private slots:
void change_stack();
private:
QStackedLayout *stackia;
}
Dialog::Dialog
{
...
connect(tombold, SIGNAL(clicked()), this, SLOT(change_stack()));
...
}
void Dialog::change_stack()
{
stackia->setCurrentIndex(1);
}
Concerning
connect(tombold, SIGNAL(clicked()), stackia, SLOT(setCurrentIndex(1)));
A slot can only have as many parameters or less parameters than a signal.
E.g. you can do
connect( sender , SIGNAL( somethingHappened( const QString& ) ),
receiver, SLOT ( doSomething ( const QString& ) ) );
and you can do
// connect signal and ignore the parameter
connect( sender , SIGNAL( somethingHappened( const QString& ) ),
receiver, SLOT ( doSomethingElse ( ) ) );
but you cannot do
// this will not work
connect( sender , SIGNAL( somethingElseHappened( ) ),
receiver, SLOT ( doSomething ( const QString& ) ) );
What you probably want is something like this:
Dialog::Dialog
{
...
// This must be a member variable
_stackia = new QStackedLayout();
tombola->setProperty( "tabpage", 1 );
tombolb->setProperty( "tabpage", 2 );
tombolc->setProperty( "tabpage", 3 );
connect( tombola, SIGNAL( clicked () ),
this , SLOT ( tombol_clicked() ) );
connect( tombolb, SIGNAL( clicked () ),
this , SLOT ( tombol_clicked() ) );
connect( tombolc, SIGNAL( clicked () ),
this , SLOT ( tombol_clicked() ) );
}
// This must be defined as slot in the header
void Dialog::tombol_clicked()
{
int index = sender()->property( "tabpage" ).toInt();
_stackia->setCurrentIndex( index );
}