Linux – Replacing a running executable in linux

linux

I have an embedded linux system that can update itself from a USB card. The interface program detects the USB insertion and looks for the upgraded executable. I currently copy it to a local file and install some commands in rc5.d to copy the file over the existing exe on the next boot. Then I have the software reboot.

Is there a better way to do this?

Best Answer

You don't need to have it copy the file over on next boot. Instead, this sequence will work fine:

  • Copy new executable to a local file.
  • Verify local file.
  • unlink() existing executable.
  • rename() new executable to the correct name.

The application will keep running after the unlink() - the kernel won't release the underlying data until all executing copies are finished.

You can then even just use execve() to have the currently-running process replace itself with the newly uploaded version.