Is there a way to determine if the process may execute a file without having to actually execute it (e.g. by calling execv(filepath, args)
only to fail and discover that errno == EACCES
)?
I could stat
the file and observe st_mode
, but then I still don’t know how that pertains to the process.
Ideally, I’m looking for a function along the lines of
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.
http://linux.die.net/man/2/access
Note the slight tricksiness around suid - if the process has effective superuser privilege it isn't taken into account, since the general idea of the function is to check whether the original invoking user should have access to the file, not to check whether this process could access the file.
Assuming your end goal is to eventually execute the program, you don't. This test would be useless because the result is potentially wrong even before the function to make the check returns! You must be prepared to handle failure of execve
due to permission errors.
As pointed out by Steve Jessop, checking whether a given file is executable can be useful in some situations, such as a file listing (ls -l
) or visual file manager. One could certainly think of more esoteric uses such a using the permission bits of a file for inter-process communication (interesting as a method which would not require any resource allocation), but I suspect stat
("What are the permission bits set to?") rather than access
("Does the calling process have X permission?") is more likely to be the interesting question...