CreateProcess函数的使用

发布时间 2023-08-26 00:19:33作者: TechNomad

CreateProcess 函数是 Windows 操作系统中用于创建新进程的核心函数之一。它提供了在一个新的进程环境中执行可执行文件的能力。以下是更详细的介绍和使用示例:

BOOL CreateProcess(
  LPCTSTR               lpApplicationName,
  LPTSTR                lpCommandLine,
  LPSECURITY_ATTRIBUTES lpProcessAttributes,
  LPSECURITY_ATTRIBUTES lpThreadAttributes,
  BOOL                  bInheritHandles,
  DWORD                 dwCreationFlags,
  LPVOID                lpEnvironment,
  LPCTSTR               lpCurrentDirectory,
  LPSTARTUPINFO         lpStartupInfo,
  LPPROCESS_INFORMATION lpProcessInformation
);

参数解释:

  • lpApplicationName: 要执行的可执行文件的路径。如果为 NULL,则使用 lpCommandLine 参数中的内容。

  • lpCommandLine: 命令行参数,包括可执行文件的路径和其他参数。

  • lpProcessAttributeslpThreadAttributes: 进程和线程的安全性属性,通常设置为 NULL。

  • bInheritHandles: 决定新进程是否继承父进程的句柄(如文件句柄、管道句柄等)。

  • dwCreationFlags: 控制新进程的创建方式,如是否创建一个新的窗口,以及如何运行新进程。

  • lpEnvironment: 新进程的环境变量,通常设置为 NULL,使其继承父进程的环境。

  • lpCurrentDirectory: 新进程的初始工作目录。

  • lpStartupInfo: 一个指向 STARTUPINFO 结构的指针,它指定了要为新进程创建的主窗口的样式、大小等信息。

  • lpProcessInformation: 一个指向 PROCESS_INFORMATION 结构的指针,用于接收有关新进程的信息,如其句柄和标识符。

下面是使用示例:

#include "main_window.h"

#include <QApplication>
#include <QDebug>
#include <windows.h>

bool create_process(const char* command, const char* work_path)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    ZeroMemory(&pi, sizeof(pi));

    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESHOWWINDOW;
    si.wShowWindow = FALSE;

    wchar_t cmd[2048] = {0};
    mbstowcs(cmd, command, strlen(command) + 1);

    wchar_t current_path[1024] = {0};
    mbstowcs(current_path, work_path, strlen(work_path) + 1);

    if(!CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, current_path, &si, &pi)) {
        qDebug() << "create process failed:" << GetLastError();
        return false;
    }

    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    return true;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString work_path = QCoreApplication::applicationDirPath();
    QString process_path = work_path + "/" + "test.exe";
    QString command = QString("%1 \"%2\" \"%3\"").arg(process_path).arg("hello").arg("world");
    bool result = create_process(command.toLatin1().data(), work_path.toLatin1().data());
    if (result) {
        qDebug() << "进程启动成功";
    }

    return a.exec();
} 

下面是被创建的进程:

int main(int argc, char* argv[]) {
    /* 打开文件以写入 */
    std::ofstream outputFile("create_process.log", std::ios::app);
    if (outputFile.is_open()) {
        if (argc != 3) {
            outputFile << "The parameter is invalid" << std::endl;
            outputFile.close();

            return 1;
        }
        /* 写入数据 */
        outputFile << argv[0] << std::endl;
        outputFile << argv[1] << std::endl;
        outputFile << argv[2] << std::endl;
    }

    outputFile.close();

    return 1;
}

运行后,启动进程: