|
![](https://www.pcbbar.com/data/attachment/common/cf/111433th11112012hdtlnn.png)
nrsbcxjbbif64023158.gif
点击上方蓝色字体,关注我们
由上图可知,testApp.c 文件的用户 ID 是 1000,用户组 ID 也是 1000。
1
修改文件所有者和组
使用 chown 和 chgrp 命令可以更改文件的所有者和组。
chown 命令示例如下:
# 将文件的所有者改为 user$ sudo chown user example.txt
# 将文件的所有者和组改为 user 和 group$ sudo chown user:group example.txtchgrp 命令示例如下:
# 将文件的组改为 group$ sudo chgrp group example.txtchown、fchown 和 lchown 函数都用于更改文件的所有者和组,但它们的作用对象和使用场景有所不同。
2
chown函数
chown 函数用于更改指定路径文件的所有者和组。
函数原型如下:
#include
int chown(const char *pathname, uid_t owner, gid_t group);
参数说明
pathname:文件或目录的路径。owner:新的用户 ID。如果设置为 -1,则不更改文件的所有者。group:新的组 ID。如果设置为 -1,则不更改文件的所属组。
返回值
成功时返回 0。失败时返回 -1,并设置 errno 来指示错误原因。
示例如下:
#include #include
int main() { const char *path = "example.txt"; uid_t new_owner = 1000; // 新的用户 ID gid_t new_group = 1000; // 新的组 ID
if (chown(path, new_owner, new_group) == -1) { perror("chown"); return 1; }
printf("Successfully changed owner and group of %s to %d:%d
", path, new_owner, new_group);
return 0;}
3
fchown函数
fchown 函数用于更改已打开文件的所有者和组。
函数原型如下:
#include
int fchown(int fd, uid_t owner, gid_t group);
参数说明
fd:文件描述符。owner:新的用户 ID。如果设置为 -1,则不更改文件的所有者。group:新的组 ID。如果设置为 -1,则不更改文件的所属组。
返回值
成功时返回 0。失败时返回 -1,并设置 errno 来指示错误原因。
示例如下:
#include #include #include
int main() { int fd = open("example.txt", O_RDWR); if (fd == -1) { perror("open"); return 1; }
uid_t new_owner = 1000; // 新的用户 ID gid_t new_group = 1000; // 新的组 ID
if (fchown(fd, new_owner, new_group) == -1) { perror("fchown"); close(fd); return 1; }
printf("Successfully changed owner and group of the file descriptor %d to %d:%d
", fd, new_owner, new_group);
close(fd); return 0;}
4
lchown函数
lchown 函数用于更改符号链接本身的所有者和组,而不是符号链接指向的文件。
函数原型如下:
#include
int lchown(const char *pathname, uid_t owner, gid_t group);
参数说明
pathname:符号链接的路径。owner:新的用户 ID。如果设置为 -1,则不更改符号链接的所有者。group:新的组 ID。如果设置为 -1,则不更改符号链接的所属组。
返回值
成功时返回 0。失败时返回 -1,并设置 errno 来指示错误原因。
示例如下:
#include #include
int main() { const char *path = "example_symlink"; uid_t new_owner = 1000; // 新的用户 ID gid_t new_group = 1000; // 新的组 ID
if (lchown(path, new_owner, new_group) == -1) { perror("lchown"); return 1; }
printf("Successfully changed owner and group of %s to %d:%d
", path, new_owner, new_group);
return 0;}
通过这些函数,可以灵活地管理文件和目录的所有者和组,进而控制访问权限。
j4mmjspgbzz64023258.jpg
vp20z1yap2i64023358.gif
点击阅读原文,更精彩~ |
|