开发者

why can a C program remove itself and then run another task?

开发者 https://www.devze.com 2023-02-21 04:53 出处:网络
#include <stdio.h> int main(int argc, char *argv[]) { printf(\"remove %s\\n\", argv[0]); remove(argv[0]);
#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("remove %s\n", argv[0]);
    remove(argv[0]);

    printf("rename %s to %s\n", argv[1], argv[2]);
    rename(argv[1], argv[2]);
}


$g++ hello.cpp -o hello
$touch tmp
开发者_Go百科$./hello tmp temp
remove ./hello
rename tmp to temp

Why is it possible?


In Unix at least (and that includes Linux and Mac OS X), if you remove a file while somebody has it open, i doesn't actually go away until the program that had it open either closes the file or terminates.


I suppose you are asking not how to do it (since you demonstrate it), but why is it possible?

The answer is that there is a difference between a program on disk (a file) and a program in memory.

When you run a program, typically, it is copied into RAM and run from there since the CPU only has direct access to execute things in RAM. This copy is conceptually independent from the file on disk and may remain in RAM even if the file is removed.

However, some OSes do not allow a file to be deleted if it represents a running application, for example Windows.

0

精彩评论

暂无评论...
验证码 换一张
取 消