系統調用 fchownat

fchownat 是linux kernel 2.6.16 以後添加的系統調用

linux kernel 2.6.16 新增了系列 at 系統調用( openat, linkat ..... )

原型:include/linux/syscalls.h

asmlinkage long sys_fchownat(int dfd, const char __user *filename, uid_t user, gid_t group, int flag);

說明:

The fchownat() function sets the owner ID and  group  ID  of
     the named  file  in the same manner as chown(). If, however,
     the path argument is relative, the path is resolved relative
     to  the  fildes  argument  rather  than  the current working
     directory.  If the fildes argument  has  the  special  value
     FDCWD,  the  path  path  resolution  reverts back to current
     working directory relative.  If the flag argument is set  to
     SYMLNK,  the  function behaves like lchown() with respect to
     symbolic links. If the path argument is absolute, the fildes
     argument  is  ignored.   If  the  path  argument  is  a null
     pointer, the function behaves like fchown().


這些 *at 系統調用相對與之前的系統調用增加了個文件描述符參數(上面的 int dfd)

功能是相對與相對與此文件描述符(目錄)的路徑而操作, 之前的系統調用的操作都是相對與進程當前位置的

當然,如果此文件描述符未設置或者不是個有效的目錄文件描述符, *at 系統調用就和老版系統調用功能相同了


一個例子展示了 openat 系統調用的用法:

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
    int dfd,ffd;
    dfd = open("/home", O_RDONLY|00200000); // 00200000其實就是 O_DIRECTORY
    if(dfd < 1)
    {
        perror("open home");
        return -1;
    }
    ffd = openat(dfd, "../opt/openat", O_CREAT, 777);
    if(ffd < 1)
    {
        perror("open new file");
        return -1;
    }
    return 0;
}

該程序創建了文件 /opt/openat

下段代碼則演示了 unlinkat 的用法:

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
    int dfd,ffd;
    dfd = open("/opt/cc", O_RDONLY|00200000);
    if(dfd < 1)
    {
        perror("open home");
        return -1;
    }
    //ffd = openat(dfd, "../opt/deny/openat", O_CREAT, 777);
    ffd = unlinkat(dfd,"../deny/openat", 0);
    if(ffd  != 0)
    {
        perror("unlinkat new file");
        return -1;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章