以编程方式将Linux缓存删除为非root用户 [英] Programmatically drop Linux cache as non-root user

查看:350
本文介绍了以编程方式将Linux缓存删除为非root用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了测试的目的,我可以通过在Linux下的procfs下写入drop_caches文件来删除缓存的内存。我只能这样做作为根。这是在嵌入式Linux上,所以没有sudo。

For testing purposes, I can drop cached memory by writing to the drop_caches file in Linux under the procfs. I can only do this as root. This is on embedded Linux so there is no sudo.

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



我可以通过编程方式在c ++中写入文件帖子 - > 如何以编程方式在Linux系统上清除C ++中的文件系统内存缓存?

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

遇到的挑战是想以非root用户身份运行应用程序时执行此操作。重新启动时,权限类似:

The challenge is wanting to do this while running the app as a non-root user. On reboot, the permissions look like:

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

您似乎不能更改这些权限 - 即使作为root:

And you cannot seem to change those permissions - even as root:

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


$ b b

如何在Linux上实现这一点?是否可以更改procfs文件的权限?如果需要,我可以完全自定义我的内核。感谢 -

How can I accomplish this on Linux? Is it possible to change permissions of a procfs file? I can fully customize my kernel if necessary. Thanks -

推荐答案

您可以创建一个辅助可执行文件(非常小心,这是危险的),任何用户都可以使用root

You can create an auxiliary executable (be very careful, it is dangerous) which any user can run it with root permissions.

这称为 setuid

出于安全考虑,您不能 setuid 一个shell脚本。

For safety reasons, you cannot setuid a shell script.

从wiki中提取如何使用它:

Extracting from the wiki how to use it:


setuid和setgid位通常用命令chmod设置
将高阶八进制数字设置为4(对于setuid)或2(对于
setgid)。 chmod 6711 file将同时设置setuid和setgid位
(2 + 4 = 6)

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)



h2>

正如@rici所说,你仍然需要执行这个过程的执行权限,所以你可以从其他并保留在 group 上。因此,只有该组的成员才能执行它。

Update

As @rici noted, you still will need to have execution permission to execute this process, so you can remove execution permission from others and keep it only on group. So, only who is member of the group can execute it.

这篇关于以编程方式将Linux缓存删除为非root用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆