创建进程执行 EXE

CreateProcess execute EXE

本文关键字:EXE 执行 进程 创建      更新时间:2023-10-16

我有一个应用程序,其中用户将文件上传到远程服务器,接收此文件的同一服务器应运行此应用程序。我正在使用创建过程方法。问题是,文件目录已经在 std :: 字符串中定义,我很难将此目录作为参数传递给 CreateProcess。

如何才能将此目录传递到创建进程而不会出错?

    //the client remotely sends the directory where the file will be saved
    socket_setup.SEND_BUFFER("nRemote directory for upload: ");
    char *dirUP_REMOTE = socket_setup.READ_BUFFER();
    std::string DIRETORIO_UP = dirUP_REMOTE; // variable where it stores the remote directory

        //after uploading this is validation for executing file
if (!strcmp(STRCMP_EXECUTE, EXECUTE_TIME_YES))
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );
    std::wstring wdirectory;
    int slength = (int)directory.length() + 1;
    int len = MultiByteToWideChar(CP_ACP, 0, directory.c_str(), slength, 0, 0);
    wdirectory.resize(len);
    MultiByteToWideChar(CP_ACP, 0, directory.c_str(), slength, &wdirectory[0], len);
    if (!CreateProcess(NULL, wdirectory.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi));
}

CreateProcess有两个版本:CreateProcessA和CreateProcessW(就像大多数类似的Windows API一样)。根据您是否启用了 Unicode,使用正确的版本。在这里,您需要先将 std::string 转换为 std::wstring,因为该 CreateProcess 实际上是一个 CreateProcessW。

std::wstring wdirectory;
int slength = (int)directory.length() + 1;
int len = MultiByteToWideChar(CP_ACP, 0, directory.c_str(), slength, 0, 0); 
wdirectory.resize(len);
MultiByteToWideChar(CP_ACP, 0, directory.c_str(), slength, &wdirectory[0], len);
//...
if (!CreateProcess(NULL,(LPWSTR)wdirectory.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi));

您也可以尝试通过手动调用 CreateProcessA 来替换 CreateProcess,并像您在问题中尝试的那样传递字符串,但这样您将不支持宽字符:

if (!CreateProcessA(NULL, directory.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi));