Replacing a running executable in 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 softw开发者_Python百科are reboot.
Is there a better way to do this?
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.
It's OK to replace the executable while the program is running IF you rm
(unlink) it first.
This is not what happens with cp
, so don't use that. Either mv
the file, or, to really be sure, rm
it and then put the new one in the same place. If you are doing this with code in the embedded software, then unlink(2)
is what you want to start with.
Unix kernels know that the inode is still in use, and they will remove the directory entry for the file but they won't release the inode (and the data blocks) until the inode reference count hits zero, and that won't happen while an instance of it is running.
This is probably not an issue with your embedded system, but as a general caution, don't count on this working for networked storage, except when on the server itself.
In linux, you can safely replace the running executable while the process is running. As long as the process is running, it that instance will continue to use the "old" code. All new calls to the application will use the "new" code. So, simply restarting the application (or the device if necessary) will use the new copy.
Note you have to be careful if your application will change config files or libraries, as those may not be resident in memory. In this case, the safer bet is to have a script do what you mentioned.
精彩评论