How does my C program check for execute permission for a given file?

Is there a way to determine if a process can execute a file without actually executing it (for example, by calling execv(filepath, args) just to fail and finding that errno == EACCES )?

I could stat save the file and watch st_mode , but then I still don't know how this relates to the process.

Ideally, I am looking for a function along the lines

 get_me_permissions(filepath, &status); // me: the process calling this function // when decoded, status tells if the process can read, write, and/or execute // the file given by filepath. 

Thanks in advance.

+4
source share
2 answers

http://linux.die.net/man/2/access

Pay attention to a little trick around suid - if the process has an effective superuser privilege, this is not taken into account, since the general idea of ​​the function is to check whether the original caller should have access to the file, and not to check if this process can get file access.

+5
source

Assuming your ultimate goal is to ultimately run the program, you will not. This test would be useless because the result is potentially incorrect even before the function returns the test! You should be prepared to handle execve crashes due to permission errors.

As Steve Jessop pointed out, checking if the executable is given can be useful in some situations, for example, in the file list ( ls -l ) or the visual file manager. Of course, one could think of more esoteric uses, such as using file permission bits for interprocess communication (interesting as a method that does not require resource allocation), but I suspect stat ("What permission bits are set to?"), And not access ("Does the calling process have X permission?") is likely to be an interesting question ...

+6
source

Source: https://habr.com/ru/post/1339572/


All Articles