May 16th, 2006

Command line redirection is performed by the command line interpreter

The magic characters like <, >, and | in command lines like

myprogram.exe | sort > output.txt

are interpreted by the command interpreter CMD.EXE; they aren’t built into the CreateProcess function. (This is obvious if you think about it. That command line created two processes; which one should CreateProcess return a handle to?)

If you pass a command line like this to CreateProcess, it will merely run the myprogram.exe program with the command line arguments “| sort > output.txt“. (The ShellExecute function behaves similarly.) If you want these characters to be interpreted as redirection operators, you need to give them to someone who will interpret those characters in the manner you intend:

cmd.exe /C myprogram.exe | sort > output.txt

Since different command line interpreters use different syntax, you have to specify which command line interpreter you want to use.

If the command line came from the user, you probably want to use the COMSPEC variable in order to give the command to the user’s command line interpreter of choice.

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.