Search code examples
c++cexecutableexecution

Program execution steps


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?


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.