Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my C program check if it has execution permission on a given file?

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.

like image 982
ladaghini Avatar asked Feb 13 '11 18:02

ladaghini


People also ask

How can you tell if a user has permission to execute a command?

First of all, look at the permissions with ls -l ... If the last/third triplet got an x ("can execute") in it, then others - and that means you - can execute it... If it's a shell-script or something like that, then others would need r ("can read") too.

How would you find if a user has permissions on a particular file?

You can run test -r /path/to/file; echo "$?" to view the return code of the test command. Use test -w to test for write permission and test -x to test for execute permission.

What are the test command to check the permission of a file?

The best way to check file permissions in Linux is using the “ls -l filename” command. This command will list all the information about this file, including the permissions. Each permission is represented by a single letter- r for read, w for write, and x for execute.

How can we know read/write permission any given file?

The Permission IndicatorsThe first three characters (2-4) represent the permissions for the file's owner. For example, -rwxr-xr-- represents that the owner has read (r), write (w) and execute (x) permission. The second group of three characters (5-7) consists of the permissions for the group to which the file belongs.


1 Answers

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...

like image 143
R.. GitHub STOP HELPING ICE Avatar answered Oct 31 '22 17:10

R.. GitHub STOP HELPING ICE