3

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?

2
  • What happens if you surround with single quotes? argv[2] = "'Use spaces and \"quotes\"'"; Nov 10, 2010 at 17:31
  • 1
    @Chris: That's not even close to C syntax.
    – Puppy
    Nov 10, 2010 at 18:06

1 Answer 1

2

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\"".

1
  • 1
    This means we have to put quotes around each string (to stop space splitting) and backslash-escape any quotes in the string. Certainly doable. I was wondering if there was something more elegant.
    – mealnor
    Nov 10, 2010 at 18:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.