How to restart a console c application written in windows?
I am using MSVS 2008. I am writing an application in c, and would like to know what's the best way to restart an application in windows.
I looked around and someone was doing somethi开发者_如何学JAVAng like this, but I am not sure if that is the best way or if that even creates a whole new process.
if(command == restart)
{
printf("program exiting!\n");
Sleep(2000);
system("cls");
WinExec("my_app.exe", SW_SHOW);
exit(0);
}
Thanks
You'll have to have one process extra for this.
From your application, you'll launch that process. It will wait for your main application to exit, then wait for whatever that it should happen (update, ...) and then restart it killing itself.
Starting app from within itself won't be ok since you won't be able to update anything.
Short answer: Looks ok to me, but if you're binding to sockets, there's a really small chance your two programs might collide before the parent exit()s.
I'm afraid asking for "the best" way is going to produce one of those "it's context-dependent" replies.
To start, according to the MSDN docs on WinExec, "This function is provided only for compatibility with 16-bit Windows. Applications should use the CreateProcess function". This implies it's a dos-era function wrapper for an 'exec'-like function. Of course CreateProcess is some kind of monster only MS would create, but if this application is going to be at all important the advice should probably be taken.
Interestingly, MS mentions in the docs for CreatProcess that "the preferred way to shut down a process is by using the ExitProcess function."
So you can see, like with so many problems, there are many solutions. Questions to answer that might hone the replies here would be:
- Do you care about platform-independence?
- Do you care about security?
- Do you care how much effort this program is supposed to take?
etc.
I hope that helps you out!
Here is some dumb example on how to start the calculator.
STARTUPINFO startUpInfo = { 0 };
PROCESS_INFORMATION procInfo = { 0 };
startUpInfo.cb = sizeof( startUpInfo );
while( 1 )
{
CreateProcess( L"C:\windows\System32\calc.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &startUpInfo, &procInfo );
WaitForSingleObject( procInfo.hProcess, INFINITE );
}
As you can see, this will start a new process "calc.exe". It will wait for it to terminate, and start it all over again. Keep on you mind that I didn't close any handles here!!!
精彩评论