When I replace a .so file used by a running PostgreSQL server it crashes When I replace a .so file used by a running PostgreSQL server it crashes unix unix

When I replace a .so file used by a running PostgreSQL server it crashes


What's the difference?

make install typically uses the install command, which deletes then re-creates the file. (This isn't inherently true, it's just how most people's Makefiles are written).

By contrast, cp just overwrites it in place.

Why does it matter?

UNIX/Linux systems mmap binaries into memory when they run. This means that the file contents are essentially directly part of the program memory. So when you overwrite the contents of an executable binary file while the program is running, things are likely to go boom in exciting ways.

By contrast, if you delete (unlink) the file, it remains mapped as an anonymous file. It still exists until the last handle to it is closed, it just doesn't have a file name anymore. The new file is then created with the same file name, but without affecting the contents of the now inaccessible unlinked file. So nothing crashes - so long as you don't have multiple instances of programs that expect to see the same version of a shared library, at least.

How to do it right?

If you insist on replacing binaries of running executables, you should do so using the install command, or with rm /the/path && cp /new/file /the/path followed by any required chown and chmod.

Demo showing the difference

Setup:

$ echo "whatevs" > blah$ touch /tmp/blah

Using install:

strace -e unlink,open,write install blah /tmp/blah...unlink("/tmp/blah")                     = 0open("blah", O_RDONLY)                  = 3open("/tmp/blah", O_WRONLY|O_CREAT|O_EXCL, 0600) = 4write(4, "whatevs\n", 8)                = 8...

vs cp:

$ strace -e unlink,open,write cp blah /tmp/blah...open("blah", O_RDONLY)                  = 3open("/tmp/blah", O_WRONLY|O_TRUNC)     = 4write(4, "whatevs\n", 8)                = 8...

Note how install unlinks the old file first? Crucial, that.

Another difference is that install won't change the contents of other links to the same underlying file, if a file has multiple hardlinks. cp will.