defaultK

[Qt 프로그래밍] QProcess 클래스를 이용한 파일 실행 본문

Qt 프로그래밍/Basic Qt

[Qt 프로그래밍] QProcess 클래스를 이용한 파일 실행

kwoss2341 2021. 3. 20. 23:08

doc.qt.io/qt-5/qprocess.html

 

QProcess Class | Qt Core 5.15.3

QProcess Class The QProcess class is used to start external programs and to communicate with them. More... Header: #include qmake: QT += core Inherits: QIODevice Note: All functions in this class are reentrant. Public Types struct CreateProcessArguments ty

doc.qt.io

 

 

 

QProcess클래스는 프로세스를 실행해주는 클래스로

실행할 프로세스 이름과 명령어 인자만 던져주면 실행할 수 있다.

 

 

QProcess의 동작원리를 알아보자

     QObject *parent;
     ...
     QString program = "./path/to/Qt/examples/widgets/analogclock";
     QStringList arguments;
     arguments << "-style" << "fusion";

     QProcess *myProcess = new QProcess(parent);
     myProcess->start(program, arguments);

 

첫번째로 지정된 QObject에 QProcess 객체를 생성한다.

생성된 QProcess는 strat() 메소드를 이용하여 Strating 상태에 들어가게 되고,

프로그램이 시작되면 QProcess는 Running 상태가 되고 started() signal을 발생한다.

프로세스가 종료되면 QProcess는 초기 상태인 NotRunning에 돌입하고 finished() signal을 발생한다.

 

 

QProcess 동작 요약)

 

QProcess 객체 생성 // 초기상태 NotRunning state

start() 메소드  -> Starting state, program start-> Running state, emit starte()

program exit  -> NotRunning state, emit finished()

 

 

추가적으로 프로세스 성격에 따라

waitForStarted() // started() 시그널이 발생하기전까지 Block

waitForReadyRead() //readyRead() 시그널이 발생하기전까지 Block

waitForBytesWritten() //버퍼에 쌓인 데이터를 디바이스에 쓰고 bytesWritten() 시그널 발생하기전까지 Block

waitForFinished() // finished() 시그널이 발생하기전까지 Block 

메소드가 필요할 수 있다.

 

 

 

예제 코드1) kwoss.cpp

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
	
	
	ofstream fout;
	fout.open("MyProcess.txt");
	
	fout<<argc<<endl;
	
	for(int i=0; i<argc; i++)
	{
		fout<<"argv["<<i<<"] = "<<argv[i]<<endl;
	}
	
	cout<<"kwoss~ finish";
	
	fout.close();
	
	
	return 0;
 } 

 

 

우선 QProcess로 실행시킬 실행파일을 만든다.

해당실행 파일은 명령어 인자들을 MyProcess.txt 파일에 출력하는 간단한 프로그램이다.

 

kwoss.cpp의 실행파일 kwoss.exe

 

 

 

예제코드2) myQprocess.pro의 main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QProcess>
#include <QFile>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);







    QString FPath = "C:/Users/**사용자경로~**/Desktop/kwoss.exe";
    QProcess *process = new QProcess(engine.rootObjects()[0]);

    if(QFile::exists(FPath))
    {
        qDebug()<<"exist!!";
        process->start(FPath,QStringList()<<"qProcess !!"<<"my"<<"sample code");
    }
    else
    {
        qDebug()<<"FPath error";
    }




    return app.exec();
}

 

해당 코드는 FPath에 실행시킬 exe파일경로를 저장한뒤

QProcess 클래스를 생성한뒤

파일 존재유무를 확인 후

strat()메소드를 이용하여 프로세스를 실행시킨다.

 

 

해당 코드를 디버그모드로 실행하면 빌드된 디버그 폴더안에

kwoss.exe가 작성한 myProcess.txt 파일을 확인할 수 있다.

 

 

출력) myProcess.txt

 

4
argv[0] = C:\Users\****\Desktop\kwoss.exe

argv[1] = qProcess !!
argv[2] = my
argv[3] = sample code

 

 

 

 

 

 

 

 

 

 

**추가 argc, argv에 대한 이해

kwonik2304.tistory.com/43?category=972965

 

[c++] main() 함수 argc, argv 명령 행 인자

docs.microsoft.com/ko-kr/cpp/cpp/main-function-command-line-args?view=msvc-160 `main` 함수 및 명령줄 인수 (c + +) `main`함수는 c + + 프로그램의 진입점입니다. docs.microsoft.com 프로그램의 main() 함..

kwonik2304.tistory.com

 

 

 

 

Comments