Solved opposite of chflags(2)

I know I can use chflags(2) to change the flags on a file. How do I find out what they are in the first place? I must be staring at the answer in the documentation but not seeing it. I know my C program can do an ls -lo on the file and then parse the returned string, but I don't want to fire up a subprocess for each file I'm examining.
 
You retrieve actual chflags of a file by a system call to (l)stat(2), the st_flags member of struct stat.

Code:
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <err.h>

#define HAS_FLAG(value, flag) \
    (0 != ((value) & (flag)))

const char *file = "/bin/sh";

int main(void) {
    struct stat sb;

    if (-1 == lstat(FILE, &sb)) {
        err(EXIT_FAILURE, "stat %s failed", file);
    }

    // test if system immutable (SF_IMMUTABLE) flag is set on it
    printf("%s is schg: %s\n", file, HAS_FLAG(sb.st_flags, SF_IMMUTABLE) ? "yes" : "no");

    // clear sunlink flag (SF_NOUNLINK) if set on it
    if (HAS_FLAG(sb.st_flags, SF_NOUNLINK)) {
        if (-1 == lchflags(file, sb.st_flags & ~SF_NOUNLINK)) {
            err(EXIT_FAILURE, "removing sunlink to %s failed", file);
        }
    }

    return EXIT_SUCCESS;
}
 
Cool. But I had actually seen that man page, and what I saw was this:

Code:
     The values for the flag are constructed by a bitwise-inclusive OR of
     flags from the following list, defined in <fcntl.h>:

     AT_SYMLINK_NOFOLLOW
             If path names a symbolic link, the status of the symbolic link is
             returned.
... and that was the only flag, so I figured it had nothing to do with cflags(2).

So now I have my answer, thanks. But the question is: should the man page for stat(2) be somehow modified?
 
Yes, the paragraph you quoted is about the flag parameter of fstatat() not st_flags.

So now I have my answer, thanks. But the question is: should the man page for stat(2) be somehow modified?
It already was :) [1]. stat(2) on 11.1-RELEASE appears to be missing an explanation of st_flags, but it's there on 12.0-CURRENT [2] at least:
Code:
     st_flags  Flags enabled for the file.  See	chflags(2) for the list	of
	       flags and their description.
[1] https://reviews.freebsd.org/rS320004
[2] https://www.freebsd.org/cgi/man.cgi...h=FreeBSD+12-current&arch=default&format=html
 
Back
Top