简体   繁体   中英

Fail to pass command line arguments in CreateProcess

I'm having trouble using CreateProcess with command line arguments. I've read to all the posts I've found but none of the solutions did work.

Here's what I have:

std::string path = "C:\\my\\path\\myfile.exe";
std::wstring stemp = std::wstring(path.begin(), path.end());
LPCWSTR path_lpcwstr = stemp.c_str();

std::string params = " Param1 Param2 Param3";
STARTUPINFO info = { sizeof(info) };
PROCESS_INFORMATION processInfo;
CreateProcess(path_lpcwstr, LPTSTR(params.c_str()), NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, NULL, NULL, &info, &processInfo);

The code works and myfile.exe (a QT Application) is opened, but argc is always 1. I've also tried specifying only the first parameter as "C:\\my\\path\\myfile.exe Param1 Param2 Param3" but that didn't work either.

Any help is greatly appreciated.

Solution: Using CreateProcessA and change the parameters accordingly fixed the problem pointed out by one of the answers.

STARTUPINFOA info = { sizeof(info) };
PROCESS_INFORMATION processInfo;
std::string path = "C:\\my\\path\\myfile.exe";
std::string params = " Param1 Param2 Param3";
CreateProcessA(path.c_str(), const_cast<char *>(config.c_str()) , NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, NULL, NULL, &info, &processInfo);

There are two versions of CreateProcess (and many other Winapi functions too):

One takes "normal" strings in ASCII/ISO88591/whatever where each character has 1 byte.
"abc" would have the numbers 97 98 99 .

The other CreateProcess takes UTF16 strings; each char has 2 or 4 byte there,
and "abc" would have the byte numbers 0 97 0 98 0 99
(UTF16 is a bit more complicated, but in this case, it´s just 0s added).
The advantage is better support for internationalization, because the
old 1-byte charsets are problematic with languages like Russian, Greek etc.

You´re using the second version. path_lpcwstr , ie. the program path and name as first parameter, is correctly provided as UTF16 string by you ( std::wstring on Windows and LPCWSTR etc. ...).

However, the second parameter with the arguments for the new process, is not UTF16 in your code (but a one-byte charset) and to avoid a compiler error, you are simply casting a pointer and telling the compiler to treat the not-UTF16 content as UTF16.
The bytes of " Param1 Param2 Param3" understood as UTF16 won´t give any sane string without proper conversion, and to start with, the 2 byte 0 value to terminate the string, as requried by Windows, is nowhere in there. The result is undefined behaviour, any strange things can happen.

Make you parameter string like you did with the path, and everything should be fine.

您是否尝试过ShellExecuteA()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM