linux中可执行文件为什么不能拷贝覆盖

对于一个普通的文件,假如有两个文件,分别是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);
    ...
}
相关推荐
翟天保Steven4 分钟前
Ubuntu-安装Epics教程
linux·ubuntu·epics
Nightwish57 分钟前
Linux随记(二十一)
linux·运维·服务器
獭.獭.2 小时前
Linux -- 文件【上】
linux·运维·服务器·进程·pcb
Johny_Zhao4 小时前
Centos8搭建hadoop高可用集群
linux·hadoop·python·网络安全·信息安全·云计算·shell·yum源·系统运维·itsm
杜子不疼.5 小时前
Linux的生态与软件安装
linux·运维·服务器
Tipriest_6 小时前
离线进行apt安装的过程(在只能本地传输的ubuntu主机上使用apt安装)
linux·运维·ubuntu·apt·install·deb
QMCY_jason6 小时前
Ubuntu 1804 编译ffmpeg qsv MediaSDK libva 遇到的问题记录
linux·ubuntu·ffmpeg
什么蜜桃绵绵冰7 小时前
linux易错题
linux·运维·服务器
Mike_Wuzy7 小时前
【Linux】发展历程
linux
嶔某7 小时前
网络:应用层
linux·服务器·网络·c++