While using the _execv() function in a C++ Windows console program, I found that the arguments are split at spaces, with each substring becoming a separate argument in the arguments list of the exec'd program. Presumably, this is not happening until after that program is found, as it is being found even when the program path argument contains spaces.
I have written a pair of programs that demonstrate the problem. The same thing happens with _spawnv(), and also if I modify the calling program to use wchar_t arrays and _wexecv().
I am building the examples as either x86 or x64 windows console application projects, using Visual Studio 2017 on Windows 10. How can I avoid this problem while using one of these functions?
// Calling program
#include "pch.h"
#include <iostream>
#include <process.h>
int main()
{
const char program[] = "C:\\Users\\dummy\\Documents\\Visual Studio 2017\\Projects\\execTest\\x64\\Debug\\testCalled.exe";
const char* arguments[] = { program, "Hello World!", nullptr }; // Note the multiple spaces
for (int a = 0; sizeof(arguments) / sizeof(*arguments) > a && arguments[a]; ++a) {
std::cerr << "Caller: " << a << " = " << arguments[a] << '\n';
}
std::wcerr << '\n';
auto rc = _execv(program, arguments);
perror("Exec fail ");
std::cerr << "return code " << rc <<'\n';
return rc;
}
// Called program
#include "pch.h"
#include <iostream>
int main( int argc, char** argv)
{
for (int a = 0; a < argc; ++a) {
std::cerr << "Called: " << a << " = " << argv[a] << '\n';
}
return 0;
}
Output:
Caller: 0 = C:\Users\dummy\Documents\Visual Studio 2017\Projects\execTest\x64\Debug\testCalled.exe
Caller: 1 = Hello World!
Called: 0 = C:\Users\dummy\Documents\Visual
Called: 1 = Studio
Called: 2 = 2017\Projects\execTest\x64\Debug\testCalled.exe
Called: 3 = Hello
Called: 4 = World!
execl
instead"\"hello world\""
worked. However i do not think that this is a generic solution.execv
,std::_Exit
should be called instead ofreturn
because the behavior is undefined if one of the functions registered usingstd::atexit
calls eitherexit()
orlongjmp(3)
._wexec*
family of functions (or_P_OVERLAY
mode with_wspawn*
) in Windows is generally a bad idea, especially for console applications (the default link target for the[w]main
entry point). NT has no equivalent to theexec*
family implemented for Windows processes, so the CRT simply spawns a new process and exits the current process. If a console-based shell is waiting on the current process, it will resume its standard I/O REPL, and now we have a mess on our hands, with two processes writing to the console and competing for access to console input.