首页 > 解决方案 > apue代码第四章umask.c运行异常

问题描述

我按照以下步骤运行 ./umask:

[root filedir]#
[root filedir]#ls
access    bar    cdpwd.c    changemod.c  devrdev.c  filetype.c  ftw8    Makefile  mycd.c  umask.c  unlink.c  zap.c
access.c  cdpwd  changemod  devrdev      filetype   foo         ftw8.c  mycd      umask   unlink   zap
[root filedir]#./umask
[root filedir]#ll foo bar
-rw-r--r--. 1 root root 0 7月  23 11:56 bar
-rw-rw-rw-. 1 root root 0 7月  23 11:56 foo

这是代码umask.c

#include "apue.h"
#include <fcntl.h>

#define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)

int
main(void)
{
    umask(0);
    if (creat("foo", RWRWRW) < 0)
        err_sys("creat error for foo");
    umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
    if (creat("bar", RWRWRW) < 0)
        err_sys("creat error for bar");
    exit(0);
}

如上面的代码,umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH),为什么 bar 对 group 和 other 有读取权限?

系统信息 :

[root filedir]#umask
0022
[root filedir]#cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core)
[root filedir]#gcc
gcc 4.8.5

Linux MiWiFi-R1CL-srv 3.10.0-957.21.3.el7.x86_64 #1 SMP Tue Jun 18 16:35:19 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

标签: clinux

解决方案


我很尴尬,我犯了一个错误。我和朋友共用一个虚拟机,他看书比我快。他运行4-12程序,代码如下:

#include "apue.h"

int
main(void)
{
    struct stat     statbuf;

    /* turn on set-group-ID and turn off group-execute */

    if (stat("foo", &statbuf) < 0)
        err_sys("stat error for foo");
    if (chmod("foo", (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0)
        err_sys("chmod error for foo");

    /* set absolute mode to "rw-r--r--" */

    if (chmod("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0)
        err_sys("chmod error for bar");

    exit(0);
}

对于这个问题,我删除了 foo 和 bar,然后运行 ​​./umask,然后一切运行良好。


推荐阅读