43. How do I run another program from my program?
This question comes up at least once a week in
the Microsoft public newsgroups. It seems simple, but there are many
options for running another program, and the differences between them can be
subtle. Basically, the available methods are as follows :
|

|
system
|
|
Passes a command to the command
interpreter (CMD.EXE on Windows NT). The simplest way of getting something
done, but you might not like the "DOS" box that pops up when you
invoke it.
|
|

|
_spawn
|
|
Part of the C runtime, _spawn
is actually a family of functions - see the runtime library help for
details. Because it's part of the CRT, it is at least portable.
|
|

|
WinExec
|
|
Obsolete in the 32-bit world,
included only for compatibility with 16 bit code.
|
|

|
ShellExecute
|
|
Part of the Win32 API,
ShellExecute is the simple launching API of choice for the foreseeable
future, because it will check against operator execute privileges under
Windows 2000.
|
|

|
ShellExecuteEx
|
|
Essentially the same as
ShellExecute, but takes a structure for a little more flexibility. One
notable extra feature is that the Ex version allows you to get a handle to
the created process.
|
|

|
CreateProcess
|
|
This is how real men
launch their processes :-). CreateProcess is the underlying API for
starting another process, and give maximum power at the expense of being a
little more troublesome to drive. .
|
The last two functions have the advantage that
you can get a process handle back from them and then wait on that handle,
allowing you to invoke another process synchronously : so you can invoke another
process, have that process run to completion, and then your original process
resumes, knowing that the child process at least ran (you have to invent your
own mechanism for finding out whether the child did what it was supposed to, of
course).
One problem can arise with this "spawn and
wait" technique - see Tip #34 for details.
