對于一個普通的文件,假如有兩個文件,分別是file和file1,我們使用 cp file1 file的方式使用file1的內容來覆蓋file的內容,這樣是可以的。
但是對于可執行文件來說,當這個文件在執行的時候,是不能通過cp的方式來覆蓋的,為什么呢 ?
如下的代碼,使用 gcc hello.c -o hello, gcc hello.c -o hello1分別編譯出兩個可執行文件hello和hello1,然后執行hello,再執行cp hello1 hello,這樣會報錯。如果可執行文件沒有被執行,那么是cp命令是可以執行成功的。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>int main() {int i = 0;while (i < 3000) {sleep(1);i++;}return 0;
}
可執行文件被執行的時候,通過execve系統調用來進行。在execve中,會調用到 deny_write_access()來禁止寫權限,而使用cp命令,會打開文件進行寫,所以操作失敗。
static struct file *do_open_execat(int fd, struct filename *name, int flags)
{...err = deny_write_access(file);...
}