Answer the question
In order to leave comments, you need to log in
How to start system with nuances?
Thanks to the previous question, it became clear (thanks to Armenian Radio ) that you can transfer a command from the code to the console using system();.
And now there is a new interest! And how to track the execution of the process that we generate from the code.
And how to start execution in the background?
Answer the question
In order to leave comments, you need to log in
#ifndef PINGERWINDOW_H
#define PINGERWINDOW_H
#include <QMainWindow>
#include <QProcess>
namespace Ui {
class PingerWindow;
}
class PingerWindow : public QMainWindow
{
Q_OBJECT
public:
explicit PingerWindow(QWidget *parent = 0);
QProcess ping;
~PingerWindow();
private:
Ui::PingerWindow *ui;
public slots:
void readyRead();
void changeHost();
void stop();
void enaStop();
void disaStop(int code);
};
#endif // PINGERWINDOW_H
#include "pingerwindow.h"
#include "ui_pingerwindow.h"
PingerWindow::PingerWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::PingerWindow)
{
ui->setupUi(this);
//Запуск процесса в фоне
ping.start("ping 127.0.0.1");
//Привязываем сигналы от кнопок
connect(ui->pingButton,SIGNAL(clicked()),this,SLOT(changeHost()));
connect(ui->stopButton,SIGNAL(clicked()),this,SLOT(stop()));
//Привязываем сигналы от процесса
connect(&ping,SIGNAL(readyRead()),this,SLOT(readyRead())); //процесс что-то написал в свой stdout
connect(&ping,SIGNAL(started()),this,SLOT(enaStop())); //процесс запустился
connect(&ping,SIGNAL(finished(int)),this,SLOT(disaStop(int))); //процесс звершил работу
}
PingerWindow::~PingerWindow()
{
stop();
delete ui;
}
void PingerWindow::readyRead()
{
//обработка сигнала о приходе новых данных - вывод их в окно
ui->pingerOut->appendPlainText(ping.readAll().data());
}
void PingerWindow::changeHost()
{
//обработка сигнала о необходимости сменить хост
stop(); //стоп процесса
ping.start(QString("ping \"%1\"").arg(ui->hostname->text())); //запуск нового процесса
}
void PingerWindow::stop()
{
//остановка процесса
if(ping.isOpen()) //если процесс открыт
{
ping.terminate(); //прекращаем его
ping.waitForFinished(); //ждем прекращения
}
}
void PingerWindow::enaStop()
{
//делаем кнопку остановки доступной, если процесс запустился
ui->stopButton->setEnabled(true);
}
void PingerWindow::disaStop(int code)
{
//после остановки процесса, выводим код возврата в окно
ui->pingerOut->appendHtml(QString("<i>Return code is %1</i>").arg(code));
//делаем кнопку остановки недоступной
ui->stopButton->setDisabled(true);
}
1. You can track it by the return code of the system function, this will be the same return that is written in main 1
2. in C++ 11, you can spawn a thread for the system
in C++ 03 std::system("start command") // under Windows
A common solution would be to use the cross-platform lib
boost::process
boost::filesystem
will help you
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question