How can a C++ binary replace itself?

TheBuzzSaw picture TheBuzzSaw · Feb 6, 2012 · Viewed 13.3k times · Source

I asked this question in a more general design context before. Now, I'd like to talk about the specifics.

Imagine that I have app.exe running. It downloads update.exe into the same folder. How would app.exe copy update.exe over the contents of app.exe? I am asking specifically in a C++ context. Do I need some kind of 3rd mediator app? Do I need to worry about file-locking? What is the most robust approach to a binary updating itself (barring obnoxious IT staff having extreme file permissions)? Ideally, I'd like to see portable solutions (Linux + OSX), but Windows is the primary target.

Answer

nabulke picture nabulke · Feb 6, 2012
  1. Move/Rename your running app.exe to app_old.exe
  2. Move/Rename your downloaded update.exe to app.exe
  3. With the next start of your application the update will be used

Renaming of a running i.e. locked dll/exe is not a problem under windows.