C++'s “system” without wait (Win32)

痞子三分冷 提交于 2019-12-01 08:10:54

问题


I have got a program which checks if there's a version update on the server. Now I have to do something like

if(update_avail) {
    system("updater.exe");
    exit(0);
}

but without waiting for "updater.exe" to complete. Otherwise I can't replace my main program because it is running. So how to execute "updater.exe" and immediately exit? I know the *nix way with fork and so on, how to do this in Windows?


回答1:


Use CreateProcess(), it runs asynchronously. Then you would only have to ensure that updater.exe can write to the original EXE, which you can do by waiting or retrying until the original process has ended. (With a grace interval of course.)




回答2:


There is no fork() in Win32. The API call you are looking for is called ::CreateProcess(). This is the underlying function that system() is using. ::CreateProcess() is inherently asynchronous: unless you are specifically waiting on the returned process handle, the call is non-blocking.

There is also a higher-level function ::ShellExecute(), that you could use if you are not redirecting process standard I/O or doing the waiting on the process. This has an advantage of searching the system PATH for the executable file, as well as the ability to launch batch files and even starting a program associated with a document file.




回答3:


You need a thread for that Look here: http://msdn.microsoft.com/en-us/library/y6h8hye8(v=vs.80).aspx You are currently writing your code in the "main thread" (which usually is also your frame code). So if you run something that takes time to complete it will halt the execution of your main thread, if you run it in a second thread your main thread will continue.

Update: I've missed the part that you want to exit immediately. execl() is likely what you want.

#include <unistd.h>

int main(){

    execl("C:\\path\\to\\updater.exe", (const char *) 0);
    return 0;
}

The suggested CreateProcess() can be used as well but execl is conforming to POSIX and would keep your code more portable (if you care at all).

#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...);

Update: tested on Win-7 using gcc as compiler



来源:https://stackoverflow.com/questions/9160833/cs-system-without-wait-win32

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!