Jagan N
Jagan N

Reputation: 2065

Handle Binary File Deletion in Code

Let's assume I've the below C code which infinitely accepts input and prints it. I use gcc to compile it to a binary, say Test. I execute this binary in a terminal and then at the same time I delete this binary from another terminal.

Is there a way to handle this deletion in code and quit the binary which is on execution?

#include <stdio.h>

int main(){
    while(1){
        // HANDLE BINARY FILE DELETION AND QUIT
        char input[50];
        scanf("%s",input);
        printf("\n%s\n",input);
    }
}

Upvotes: 0

Views: 73

Answers (1)

John Bollinger
John Bollinger

Reputation: 180286

Is there a way to handle this deletion in code and quit the binary which is on execution?

C provides no mechanism specifically to recognize or respond to operations on the on-disk image of a program that is running, if such a thing even exists. You could conceivably attempt to identify that file via argv[0] (which is not guaranteed to be successful), and periodically check it. You might even find a third-party library or system-specific mechanism for registering to receive a signal when the binary discovered in that way is modified or deleted. None of that is built into C, however.

Some operating systems might prevent such a deletion in the first place, or even provide the behavior you describe at the OS level. Overall, though, what you propose is simply something that you should not expect or rely on to happen. The on-disk image of a program is pretty much a separate thing from running processes.

Upvotes: 5

Related Questions