parallely run an application while it starts another application in c++ - c++

I am trying to write an application program that can start another application using c++ in linux . Starting another application is not the problem . The problem I am facing is, that the parent application pauses till the child application is closed. I want the parent application to run along with the child application so that more functionalities of the parent application can be used. How do i go about it?
It would help me a lot if somebody could give me an idea on this.
The application consists of two files main.cpp and a virtualbotmain.cpp. The part of the
virtualbotmain.cpp: #include <iostream>
#include <stdlib.h>
VirtualBotMain::VirtualBotMain(QWidget *parent) :
QWidget(parent),
ui(new Ui::VirtualBotMain)
{
ui->setupUi(this);
}
void VirtualBotMain::on_enterButton_clicked()
{
QString enterString = ui->enterEdit->text();
ui->convoText->append("User: " + enterString);
ui->enterEdit->setText("");
if(enterString=="word")
{
ui->convoText->append("Joe: done..!!");
system("gedit");
}
}
The main.cpp is :
#include <QtGui/QApplication>
#include "virtualbotmain.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
VirtualBotMain w;
w.show();
return a.exec();
}
This is a GUI application that can be used to just type in the application i am trying to open and the application will do it for me. So trying to open many applications one after the other is becoming a problem as the GUI application won't work untill i close the previously opened application.

If you're using a system call (or a similar way to invoke the shell), you can apply the same logic you'd apply in your terminal to start a process "in the background":
system("./myProgram &");
// ^
// run in background
Better alternatives include forking, though it really depends on your specific requirements, which we do not know.

#include <stddef.h>
#include <process.h>
int status = spawnl( P_NOWAIT, "myprog", "myprog", "ARG1", "ARG2", NULL );

Related

Modbusclient as a console application, "Stuck in Connectingstate loop"

I'm trying hardly to convert the Modbusmaster example (qt example) which is a widget application to a console application. I wanted to build a connection between a local slave and my master. The problem I'm facing is that my code is changing its state to “Connecting state” ,gets stuck and doesn't want to build a connection. That's why, I recon that the Modbus library is limited and it's only compatible with the widget form.
Could someone tell me if my guesses are right.
down below you will find my code:
#include <QCoreApplication>
#include <QDebug>
#include <QModbusDataUnit>
#include<iostream>
#include <QTimer>// this bib was add to the 50ms Loop check
#include <string>
#include <QString>
#include <QThread>
#include <QModbusTcpClient>
#include <QModbusDataUnit>
#include <QUrl>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Mainmodbus T ;
T.modbusDevice = new QModbusTcpClient();
if (!T.modbusDevice) qDebug()<<"error 1";
if (T.modbusDevice->state() != QModbusDevice::ConnectedState) {
T.modbusDevice->setConnectionParameter(QModbusDevice::NetworkAddressParameter, "127.0.0.1");
T.modbusDevice->setConnectionParameter(QModbusDevice::NetworkPortParameter, 502);
T.modbusDevice->connectDevice();
while(true){
qDebug()<<T.modbusDevice->state();}
}
return a.exec();
}
I can be wrong but I think the QModbusDevice::ConnectingState you see actually means your server is up and running and waiting for a connection.
I guess what you are missing is opening a connection from a Modbus client. You can do that with different tools, I guess running the client example
would be a good idea. Otherwise, you can use QModMaster or any other tool you like.
Once you open the connection from the client the state on your server should change to QModbusDevice::ConnectedState.
Be aware that the server you built is just an empty shell, there is no register map defined so if you query the contents of any register from the client you will get an error.
At the very minimum, you should at least define a map with some default values or get them from command-line options. To do that you need to look at the server example a bit more carefully.
First you need to define the register map with something like this:
QModbusDataUnitMap reg;
reg.insert(QModbusDataUnit::Coils, { QModbusDataUnit::Coils, 0, 10 });
reg.insert(QModbusDataUnit::DiscreteInputs, { QModbusDataUnit::DiscreteInputs, 0, 10 });
reg.insert(QModbusDataUnit::InputRegisters, { QModbusDataUnit::InputRegisters, 0, 10 });
reg.insert(QModbusDataUnit::HoldingRegisters, { QModbusDataUnit::HoldingRegisters, 0, 10 });
modbusDevice->setMap(reg);
setupDeviceData();
And then for the setupDeviceData(); you can copy the function in the example but instead of taking the data from the widget, you will have to load default values or something from the command line.
In answer to your question: no, there should be no limitation and you should be able to run the server from the command line. I wonder why somebody on his/her right mind would want to do that when you have excellent alternatives like libmodbus. But honestly, I won't miss much sleep wondering.

Observe changes in QSharedMemory

I have a QSharedMemory to prevent that two processes of my application are running at the same time. Process A sets the QSharedMemory to "locked" when started. Now my process B sets a value like "please come back to foreground".
Is there an easy way for process A to observe changes in the QSharedMemory, i.e. avoids implementing a stupid pulling timer?
Here we are: QSystemSemaphore
Like its lighter counterpart QSemaphore, a QSystemSemaphore can be accessed from multiple threads. Unlike QSemaphore, a QSystemSemaphore can also be accessed from multiple processes.
Like QSharedMemory, QSystemSemaphore uses a key-based access method.
Instead of using shared memory, the process could open a QLocalSocket to a named local server, and when it fails, open a QLocalServer. All subsequent processes will success to open the socket to the server, and can communicate with it. That's probably the simplest, most portable way of accomplishing the job.
You can also use QtSingleApplication, iff it has been ported to Qt 5.
To answere your question: No, QSharedMemory does not have such a feature.
If you just want to have a "single instance" application, you can use https://github.com/Skycoder42/QSingleInstance.
It makes shure you have only 1 instance of you application at a time, can automatically bring the active window to the front and allows you to pass parameters from the new process to the running one.
Simple example:
#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include <qsingleinstance.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSingleInstance instance;
MainWindow *w = NULL;
instance.setStartupFunction([&]() -> int {
w = new MainWindow(NULL);
instance.setNotifyWindow(w);
w->show();
return 0;
});
QObject::connect(qApp, &QApplication::aboutToQuit, [&](){
delete w;
});
QObject::connect(&instance, &QSingleInstance::instanceMessage, [&](QStringList args){
QMessageBox::information(w, "Message", args.join('\n'));
});
return instance.singleExec();
}
This will show the mainwindow, just like you woudl expect. If the application is run a second time, the currently running mainwindow will be raised to the foreground and a messagebox with the arguments will be shown.
Note: This example uses the QWidgets, but the QSingleInstance can be used with a gui or core application, too.

Application freeze in 3rd party library call

I am working on a c++ measurement software which uses a 3rd party API for the interface all sensors are connected to. This API is not open source and no debug library is available.
In some occasions, the software freezes when starting to read a value from the interface. While I could not determine what criterions cause the problem and why it only happens sometimes so far, I'd like to intercept the freezing and implement some error handling, which would also allow me to better debug the issue.
In my code, I simply have a call
BOOL result = false;
result = pciadioAIStartConversion(board_index, channel_nr, range);
where, if the error occurs, pciadioAIStartConversion never returns. I am looking for some simple functionality to keep the software running and return if the call takes to long.
I am using the Qt framework (4.8.6) so a possible solution would be using the event system and a QTimer, but therefore the call would need its own thread if I'm not mistaken and that seems like overkill to me.
piezol is right You need a separate thread which can be quite a mess but the good news is that Qt thread framework (which is called QtConcurrent) is really helpful.
Here is an example for running a standard function in a separate thread mantaining control of it.
#include <QDebug>
#include <QThread>
#include <QString>
#include <qtconcurrentrun.h>
#include <QApplication>
using namespace QtConcurrent;
void hello(QString name)
{
qDebug() << "Hello" << name << "from" << QThread::currentThread();
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QFuture<void> f1 = run(hello, QString("Alice"));
QFuture<void> f2 = run(hello, QString("Bob"));
f1.waitForFinished();
f2.waitForFinished();
}

Restoring or bringing to front Qt desktop application

I have made my app into a single instance app using the RunGuard code found on this SO question:
Qt: Best practice for a single instance app protection
What I'd like to do is when the user tries to start the application while there is one running is to bring the existing running application to the front, and if minimised, restore it.
In my Delphi Windows programming days I used to broadcast a Windows message from the new application before closing it. The existing app would receive this and restore itself and come to the front.
Is something like this possible with Qt on Windows and Linux platforms?
Did you have any specific trouble with QtSingleApplication? It should be sufficient for what you want and will enable you to send a message to the running application. You just need a slot to get that message and if it matches what you expect then you restore it.
http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication-example-trivial.html
The logview object is also set as the application's activation window. Every time a message is received, the window will be raised and activated automatically.
For some reason setActivationWindow() and activateWindow() don't work for me. This is my workaround:
#include <QWidget>
#include <qtsingleapplication.h>
class Window : public QWidget
{
Q_OBJECT
public:
Window(QWidget *parent = 0) : QWidget(parent) {}
public slots:
void readMessage(const QString &str) { showNormal(); }
};
int main(int argc, char *argv[])
{
QtSingleApplication instance(argc, argv);
Window *window = new Window;
window->show();
QObject::connect(&instance, SIGNAL(messageReceived(const QString &)), window, SLOT(readMessage(const QString &)));
if (instance.sendMessage(""))
return 0;
return instance.exec();
}
#include "main.moc"
In common, it is not possible without IPC. QtSingleApplication provide such IPC, but you will get extra dependency from QtNetwork module. (As #svlasov answered)
First problem that you will have: you can't raise any window of application if this application is not foreground. There are solutions for Windows and OS X, how to force raising of windows.

Qt application with optional gui

I am going to write program using Qt for some image processing and I want it to be able to run in non-gui mode (daemon mode?). I'm inspired by VLC player, which is "typically" GUI program, where you can configure it using GUI, but you can also run it in non-gui option when it runs without GUI. Then it uses some configuration file created in GUI mode.
Question is how should be such a program design? Should be some program core, which is GUI independent and depending on options it is being connected with GUI interface?
Yes, you could use a "headless" or "gui" option for the binary using QCommandLineParser. Note that it is only available from 5.3, but the migration path is pretty smooth within the major series if you still do not use that.
main.cpp
#include <QApplication>
#include <QLabel>
#include <QDebug>
#include <QCommandLineParser>
#include <QCommandLineOption>
int main(int argc, char **argv)
{
QApplication application(argc, argv);
QCommandLineParser parser;
parser.setApplicationDescription("My program");
parser.addHelpOption();
parser.addVersionOption();
// A boolean option for running it via GUI (--gui)
QCommandLineOption guiOption(QStringList() << "gui", "Running it via GUI.");
parser.addOption(guiOption);
// Process the actual command line arguments given by the user
parser.process(application);
QLabel label("Runninig in GUI mode");
if (parser.isSet(guiOption))
label.show();
else
qDebug() << "Running in headless mode";
return application.exec();
}
main.pro
TEMPLATE = app
TARGET = main
QT += widgets
SOURCES += main.cpp
Build and Run
qmake && make && ./main
qmake && make && ./main --gui
Usage
Usage: ./main [options]
My program
Options:
-h, --help Displays this help.
-v, --version Displays version information.
--gui Running it via GUI.
You can pass an argument to your application when starting to show in gui or non-gui modes. For example if you pass -non-gui parameter when running in command line then the application should not show the main window and it should do some other stuff :
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
bool GUIMode=true;
int num = qApp->argc() ;
for ( int i = 0; i < num; i++ )
{
QString s = qApp->argv()[i] ;
if ( s.startsWith( "-non-gui" ) )
GUIMode = false;
}
if(GUIMode)
{
w.show();
}
else
{
//start some non gui functions
}
return a.exec();
}
The example by lpapp above didn't work for me, as I got
qt.qpa.screen: QXcbConnection: Could not connect to display localhost:10.0
Could not connect to any X display.
when running without an X display (any value for DISPLAY, not just localhost:10.0).
There was a workaround - export QT_QPA_PLATFORM='offscreen' - but that's not a command line option, your user is expected to do it, which isn't nice.
So, following posting a question here, further research lead me to the following QT5 document that explains the "approved" way to start up with or without a GUI depending on command line options:
https://doc.qt.io/qt-5/qapplication.html#details
However, your mileage may vary. The example there didn't "just work" for me, either!
I had to use the command line arg to then choose one of two methods to run. Each method created its own app object (QCoreApplication for headless, QApplication for GUI, as the docs show) and then running the app.
It may be because I'm working with "mostly Qt 4" code and compiling on Qt 5 that things are being a bit odd but this method now works, so I've not investigated further.
With Qt5, running a Qt application with the command line argument -platform offscreen does draw offscreen.
See the documentation https://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
The options currently supported are the following:
-platform platformName[:options], specifies the Qt Platform Abstraction (QPA) plugin.
Overrides the QT_QPA_PLATFORM environment variable.
The supported platform names are listed in the platformName docs.
Tested with Qt 5.15.1