Question

I have a c++ program that works fine, however it needs to run for a long time. But while it is running I could continue to develop some parts of it. If I recompile my program, this will replace the binary with a new one. Does this will modify the behavior of the running program? Or are the process and the binary file two separate things once the program is launched?

More generally, what are the steps of a program execution?

Was it helpful?

Solution

On Linux, the process uses memory mapping to map the text section of the executable file and shared libraries directly into the running process memory. So if you could overwrite the executable file, it would affect the running process. However, writing into a file that's mapped for execution is prohibited -- you get a "Text file busy" error.

However, you can still recompile the program. If the compiler (actually the linker) gets this error, it removes the old executable file and creates a new one. On Unix, if you remove a file that's in use, the file contents are not actually removed from the disk, only the reference from the directory entry is removed; the file isn't fully deleted until all references to it (directory entries, file descriptors and memory mappings) go away. So the running process continues to be mapped to the old, nameless file. You can see this with the following demonstration:

barmar@dev:~$ ls -li testsleep
229774 -rwxr-xr-x 1 barmar adm 4584 Apr 24 04:30 testsleep
barmar@dev:~$ ./testsleep &
[1] 17538
barmar@dev:~$ touch testsleep.c
barmar@dev:~$ make testsleep
cc     testsleep.c   -o testsleep
barmar@dev:~$ ls -li testsleep
229779 -rwxr-xr-x 1 barmar adm 4584 Apr 24 04:32 testsleep

The inode number changed from 229774 to 229779 when I recompiled the program while it was running, indicating that a new file was created.

OTHER TIPS

On Windows, you couldn't even write the new executable while the old version is running. The file on disk is locked while the process exists. On Linux, you can overwrite the file on disk, but the copy in memory remains untouched.

OTOH, while running in an IDE, it may be possible to patch the running process as the IDE is aware of the relevant details. But it's complex and not all IDE's support this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top