CreateProcess执行EXE

时间:2015-01-13 01:35:22

标签: c++ createprocess

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

如何将此目录无错误地传递给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));
}

1 个答案:

答案 0 :(得分:1)

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并像你在问题中尝试的那样传递cstring,但是你不会支持宽字符:

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