接下来讲的函数主要是用来更改文件的用户ID和,组ID。
#include <unistd.h>
int chown(const char* pathname,uid_t owner,gid_t group);
int fchown(int filedes,uid_t owner,gid_t growp);
int lchown(const char* pathname,uid_t owner,gid_t group);
成功返回0,若出错则返回-1
查看GNU C手册
int chown (const char *filename, uid t owner, gid t group) [Function]
The chown function changes the owner of the file filename to owner, and its group
owner to group.
Changing the owner of the file on certain systems clears the set-user-ID and set-group-
ID permission bits. (This is because those bits may not be appropriate for the new
owner.) Other file permission bits are not changed.
The return value is 0 on success and -1 on failure. In addition to the usual file name
errors (see Section 11.2.3 [File Name Errors], page 224), the following errno error
conditions are defined for this function:
EPERM This process lacks permission to make the requested change.
Only privileged users or the file’s owner can change the file’s group. On
most file systems, only privileged users can change the file owner; some
file systems allow you to change the owner if you are currently the owner.
When you access a remote file system, the behavior you encounter is
determined by the system that actually holds the file, not by the system
your program is running on.
See Section 31.7 [Optional Features in File Support], page 771, for information
about the _POSIX_CHOWN_RESTRICTED macro.
EROFS The file is on a read-only file system.
int fchown (int filedes, int owner, int group) [Function]
This is like chown, except that it changes the owner of the open file with descriptor
filedes.
The return value from fchown is 0 on success and -1 on failure. The following errno
error codes are defined for this function:
EBADF The filedes argument is not a valid file descriptor.
EINVAL The filedes argument corresponds to a pipe or socket, not an ordinary
file.
EPERM This process lacks permission to make the requested change. For details
see chmod above.
EROFS The file resides on a read-only file system.
其实 ,我们可以看到,大多数函数失败了是返回小余0的数,而并完全是-1.所以,当你判断一个函数是否出错的时候记得使用(<0),而不是-1;
特别说明一下lchown是改变符号链接本身的所有者,而不是该符号链接所指向的文件。
如果两个参数owner,和group中的任一一个是-1,则对应的ID不变。
基于BSD的系统规定,只有超级用户才能更改一个文件的所有者。这样做的原因是泛指用户改变其文件的所有者从而百度哦磁盘空间限额对他们的限制。系统V则允许任一用户更改他们所拥有的文件的所有者。
若_POSIX_CHOWN_RESTRICTED对指定的文件起作用。
(1)只有超级用户进程能更改文件的用户ID
(2) 若满足下列条件,一个非超级用户进程就可以更改文件的组ID:
(a)进程拥有此文件(其有效用户ID,等于该文件的用户ID)
(b)参数owner等于-1或者文件用户ID,并且参数group等于进程的有效组ID或者进程的附加组id之一。
这意味这,当_POSIX_CHOWN_RESTRICTED起作用的时你不能更改其他用户的文件的用户id,你可以更改你所拥有的文件的组ID,但只能改到你所属的组。
如果这些函数由超级用户进程调用。则在成功返回的时候,该文件的设置用户ID位和设置组id,为都会被清除。
shell中使用chown的时候,格式如下
chown 属主 文件名
更多请访问:http://blog.csdn.net/wallwind