c++ - 以非 root 用户身份以编程方式删除 Linux 缓存

标签 c++ linux permissions embedded-linux procfs

出于测试目的,我可以通过在 Linux 中的 procfs 下写入 drop_caches 文件来删除缓存内存。我只能以 root 身份执行此操作。这是在嵌入式 Linux 上,因此没有 sudo。

sync; echo 3 > /proc/sys/vm/drop_caches

我可以通过在帖子中执行某些操作,以 C++ 编程方式写入文件 --> How to programmatically clear the filesystem memory cache in C++ on a Linux system?

sync();
std::ofstream ofs("/proc/sys/vm/drop_caches");
ofs << "3" << std::endl;

挑战在于想要在以非根用户身份运行应用程序时执行此操作。重新启动时,权限如下所示:

# cd /proc/sys/vm/
# ls -lrt drop_caches 
-rw-r--r--    1 root     root             0 Feb 13 19:50 drop_caches

而且您似乎无法更改这些权限 - 即使是 root:

# chmod 777 drop_caches 
chmod: drop_caches: Operation not permitted
# chown user:user drop_caches 
chown: drop_caches: Operation not permitted

如何在 Linux 上完成此操作?是否可以更改 procfs 文件的权限?如有必要,我可以完全自定义我的内核。谢谢-

最佳答案

您可以创建一个辅助可执行文件(非常小心,这很危险),任何用户都可以使用 root 权限运行它。

这叫做 setuid .

出于安全原因,您不能setuid shell 脚本。

从wiki中提取如何使用它:

The setuid and setgid bits are normally set with the command chmod by setting the high-order octal digit to 4 (for setuid) or 2 (for setgid). "chmod 6711 file" will set both the setuid and setgid bits (2+4=6)

更新

正如@rici 指出的那样,您仍然需要具有执行权限才能执行此过程,因此您可以从others 中删除执行权限,并将其仅保留在group 上。因此,只有组成员才能执行它。

关于c++ - 以非 root 用户身份以编程方式删除 Linux 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14861880/

相关文章:

c++ - 调试/跟踪嵌入式 sql

C++ 在析构函数中序列化是个坏主意,如果是,为什么?

linux : how to compress each file individually in an archive tar/cpio/. ..其他

从终端编译 C 代码,返回 fatal error ?

android 互联网权限不起作用

php - Web 应用程序,用户上传文件夹最安全的地方

c++ - QT:无法在启动/停止按钮中终止 Qprocess

c++ - 在 map 中如何将相同值的键收集到 vector 中?

linux - PPSS 外壳脚本

android - 如何删除Android中不必要的权限?