Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a simple shell command

Tags:

winapi

What is the best WinAPI function to use when you only want to run a simple shell command like hg > test.txt?

like image 767
Paul Manta Avatar asked Aug 10 '11 20:08

Paul Manta


3 Answers

To simply run a file, then ShellExecute() and CreateProcess() are the best options.

As you want to redirect output to a file/run a shell command, it complicates things...

Output redirection is a feature of the command prompt, and as such, the command you want to run needs to be passed to cmd.exe (on NT/XP+) passing /c and your command as the parameters (either ShellExecute or CreateProcess will do).

cmd /c "ipconfig >c:\debug\blah.txt"

The best way however is to use CreateProcess() and create your own pipes to talk to the stdin and stdout of the program (This is all cmd does internally)

like image 66
Deanna Avatar answered Oct 15 '22 02:10

Deanna


You could use ShellExecute(), but why not try system() first? I am not so sure that ShellExecute() can actually do piping or redirection. There is also CreateProcess(), but that requires a bit more work. CreateProcess() gives you the best control, though.

like image 30
Rudy Velthuis Avatar answered Oct 15 '22 01:10

Rudy Velthuis


There are two ways of issuing commands: the Windows Shell way, and the command line way.

Windows Shell issues commands by executing verbs on files. Verbs are associated with file types in the registry. Examples of common verbs are Open and Print. The WinAPI to use for this is ShellExecute. Windows Shell does not help you pipe the output of a process to a file. You can do it using CreateProcess, but it is a little bit involved.

The command line way is to use the system function.

like image 42
Don Reba Avatar answered Oct 15 '22 03:10

Don Reba