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);
    ...
}
相关推荐
A.A呐5 小时前
【Linux第六章】进程状态和优先级
linux
iambooo5 小时前
Shell在日志分析与故障排查中的实战应用
linux·服务器·网络
一路往蓝-Anbo6 小时前
第 9 章:Linux 设备树 (DTS) ——屏蔽与独占外设
linux·运维·服务器·人工智能·stm32·嵌入式硬件
钛态6 小时前
Flutter for OpenHarmony:dio_cookie_manager 让 Dio 发挥会话管理能力,像浏览器一样自动处理 Cookie 深度解析与鸿蒙适配指南
android·linux·运维·flutter·ui·华为·harmonyos
王码码20356 小时前
Flutter for OpenHarmony:Flutter 三方库 bluez 玩转 Linux 风格的蓝牙操作(蓝牙底层互操作)
linux·运维·服务器·前端·flutter·云原生·harmonyos
A.A呐6 小时前
【Linux第七章】进程切换和命令行参数
linux
抓饼先生6 小时前
iceoryx编译和验证
linux·c++·零拷贝·iceoryx
栈低来信7 小时前
SLUB分配器
linux
吕司7 小时前
Linux信号产生
linux·运维·服务器
A.A呐7 小时前
【Linux第九章】程序地址空间
linux