moogoo
moogoo

Reputation: 85

Update program by writing to the currently executing file

I am writing a c++ program which sooner or later will need to be updated. I want this to require as little interaction with the user as possible since the program runs constantly in the background and never terminates. I know that under normal circumstances, you can't write to a file that's being executed, so this is my question: is it possible for an application to modify itself without just running another executable and letting that one take over? I can't have more than one file.

Upvotes: 4

Views: 3148

Answers (3)

SirDarius
SirDarius

Reputation: 42959

Most programs using auto-update features use another executable to take over execution in order to avoid that problem.

However I see a somewhat simple solution:

  • old program downloads new program into a temporary location
  • old program starts new program (possibly with a special parameter) and terminates itself
  • new program copies itself over old program (it should be ok for a running program to read itself, as long as it doesn't open itself for writing)
  • new program runs new program (copy) with a special argument, and then terminates itself
  • new program (copy) deletes new program and resumes normal operations

Is it clear enough ? :)

Upvotes: 6

Puppy
Puppy

Reputation: 146988

There are some languages like scripting languages or .NET/Java that can allow you to modify your own code. However, C++ does not provide any runtime code generation or modification tools. If you don't want to change language, you're stuffed. It's possible that you could get some nonstandard tool like LLVM to do it, I guess.

Upvotes: 0

siride
siride

Reputation: 209895

You should be able to send a command to the program to tell it to terminate, then update the executable file, then relaunch. It should also save any state so that it can continue where it left off when you restart it, if that matters.

Upvotes: 0

Related Questions