views:

36

answers:

2

I have an existing utility application, let's call it util.exe. It's a command-line tool which takes inputs from the command line, and creates a file on disk, let's say an image file

I want to use this within another application, by running util.exe. However it needs to be synchronous so the file is known to exist when processing continues.

e.g (psudeo)

bool CreateImageFile(params)
{
  //ret is util.exe program exit code
  int ret = runprocess("util.exe",params);
  return ret==0;
}

Is there a single Win32 API call that will run the process and wait until it ends? I looked at CreateProcess but it returns as soon as it tries to start, I looked at ShellExecute but that seems a bit ugly even it were synchronous.

+1  A: 

Process handle is a waitable object, AFAIK. This is exactly what you need.

However, I'd recommend against doing anything like that. Starting process on windows may be slow and it will block your UI. Consider a PeekMessage loop with 50ms wait timeouts to do it from a windows application.

Pavel Radzivilovsky
http://support.microsoft.com/kb/125212 this confused me. I see a few places online using WaitForSingleObject but that page says this no longer works; or is that _only_ talking about spawning 16-bit exes in 32bit?
John
How does a message loop help - I still have to spawn the process somehow? Also, if the whole point is my application pauses while the file is generated, it should be ok to block?
John
Creating the process on Windows may be slow but is probably not comparable to the time taking the process to terminate. So it's not where to put CreateProcess() which is critical here, but WaitForSingleObject(). Anyway, are you writing a GUI application or a console one? (it's of course OK to block a simple, sequential console application)
Nikola Gedelovski
+1  A: 

There's no single api, but this is actually a more interesting general question for Win32 apps. You can use CreateProcess or ShellExecuteEx and WaitForSingleObject on the process handle. GetExitCodeProcess at that point will give you the program's exit code. See here for simple sample code.

However this blocks your main thread completely, and can give you serious deadlock problems under some Win32 messaging scenarios. Let's say the spawned exe does a broadcast sendmessage. It can't proceed until all windows have processed the message - but you can't proceed because you're blocked waiting for it. Deadlock. Since you're using purely command line programs this issue probably doesn't apply to you though. Do you care if a command line program hangs for a while?

The best general solution for normal apps is probably to split a process launch-and-wait off onto a thread and post a message back to your main window when the thread runs to completion. When you receive the message, you know its safe to continue, and there are no deadlock issues.

Bob Moore