I have a Q_Object class. In this class, I want to start and stop a process with the send and stop function
My send function is working fine and when I click it my process is running but when I click on the stop function it is not working because I do not have access to the processId How can I fix this problem??
class Simulator : public QObject
{
Q_OBJECT
public:
explicit Simulator(QObject *parent = nullptr);
~Simulator();
EnvHandler *envHandler = new EnvHandler;
signals:
public slots:
Q_INVOKABLE void send();
Q_INVOKABLE void stop();
private:
QProcess *m_process;
qint64 pId;
};
#include "Simulator.h"
#include <QThread>
#include <iostream>
#include <thread>
#include <QTimer>
#include <fstream>
Simulator::Simulator(QObject *parent)
: QObject{parent} , m_process(new QProcess(this))
{
}
void Simulator::send()
{
QString path = envHandler->env_MERSAD_HOME() +"/Bin/Module/DataGenerator";
m_process->startDetached(path);
pId = m_process->processId();
}
void Simulator::stop()
{
QString command = "kill -9 " + QString::number(pId);
m_process->execute(command);
}
Simulator::~Simulator()
{
}
The problem appears to be that you are trying to retrieve the process ID after the process is detached. You can change the way you are calling startDetached so that it provides you the ID. Then you should be able to kill it.
void Simulator::send()
{
QString path = envHandler->env_MERSAD_HOME() +"/Bin/Module/DataGenerator";
m_process->setProgram(path);
m_process->startDetached(&pId);
}