On Unix, we can create a new process with fork(); execvp(argv[0], argv); (with a bit of plumbing working out if we are the parent or child following the fork). In the child process, main(argc, argv) will see the strings exactly as they were passed to execvp.
On Windows, the _spawn() family basically implements fork(); exec(); in one step. So far, so nice. The problem is that by the time we get to main() in the child, our strings are not what they were. Let me开发者_开发问答 give an example.
argv[0] = "foo";
argv[1] = "bar";
argv[2] = "Use spaces and \"quotes\"";
_spawnvp(0, argv[0], argv);
When we get to the child, in main() we will find that, in this example, argv[0] and argv[1] are as expected, but argv[2] has been tokenized on spaces and quotes removed such that
argv[2] == "Use"
argv[3] == "and"
argv[4] == "quotes"
How can I pass an argv structure from the parent to child as is, with it being reinterpreted and altered?
According to the Note on MSDN's documentation, if you want a string which contains spaces to be passed as a single argument, you need to quote it.
Spaces embedded in strings may cause unexpected behavior; for example, passing _spawn the string "hi there" will result in the new process getting two arguments, "hi" and "there". If the intent was to have the new process open a file named "hi there", the process would fail. You can avoid this by quoting the string: "\"hi there\"".
精彩评论