Programmatically drop Linux cache as non-root user

夙愿已清 提交于 2019-12-10 14:44:20

问题


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

I can write to the file programmatically in c++ by doing something from the post --> 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;

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

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

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 -


回答1:


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

This is called setuid.

For safety reasons, you cannot setuid a shell script.

Extracting from the wiki how to use it:

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)

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.



来源:https://stackoverflow.com/questions/14861880/programmatically-drop-linux-cache-as-non-root-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!