我非常了解如何直接从命令行使用 chmod
。但我不太确定我们是否可以模仿它
chmod o+t filename
函数。我通常直接调用它:
chmod(filename, 0666)
但是我不想设置权限,而是想知道如何在不影响其他权限的情况下添加权限,例如 chmod o+t filename
。 chmod(filename, 1777)
之类的东西也会设置粘滞位,但它也会设置所有其他位。我们应该将什么数字传递给 chmod
以让它只更改粘滞位?提前致谢。
最佳答案
如评论中所述,首先使用 stat() 读取当前模式位,然后执行 chmod()。
要带回家的是,您不应该直接使用数值,而应该相信头文件中定义的数值。有关可用内容,请参见 man 2 chmod
。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv) {
struct stat st;
if(argc < 1) return 2;
if(stat(argv[1], &st) != 0) {
perror(argv[1]);
return 2;
}
printf("mode before chmod() = %o\n", st.st_mode);
if(chmod(argv[1], st.st_mode | S_ISVTX) != 0) {
perror(argv[1]);
return 1;
}
if(stat(argv[1], &st) != 0) {
perror(argv[1]);
return 2;
}
printf("mode after chmod() = %o\n", st.st_mode);
return 0;
}
祝您作业愉快!
关于linux - chmod 系统调用需要数字参数以仅更改粘滞位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22189223/