Embedding a Unix Shell in C: Check if a File Is Executable

I am working on an implementation of the Unix shell in C, and I'm currently dealing with the problem of relative paths. Especially when entering commands. At the moment, I have to enter the full path to the executable every time I would rather put "ls" or "cat".

I managed to get the env $ PATH variable. My idea is to split the variable into a ":" character, and then add each new line to the command name and check if the file exists and is executable.

For example, if my PATH is "/ bin: / usr / bin" and I enter "ls", I would like the program to first check if "/ bin / ls" exists and is executable if you don’t go to "/ usr / bin / ".

Two questions:

1) Is this a good way to do this? (Is it not necessary to be the best. I just want to make sure that it works.

2) More importantly, How can I check in C if the file exists and is executable?

Hope I'm clear enough and ... well thanks :)

+3
source share
6 answers

not to do. This check is incorrect; he is inherently subject to race conditions. Instead, tryexec making it with the appropriate -family call. If it is not executable, you will receive an error message.

Also note that you do not need to search on your own PATH; execvpcan do it for you.

+8
source

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

:.

struct stat sb;
if(!stat(path, &sb))
{
  if(IS_REG(sb.st_mode) && sb.st_mode & 0111)
    printf("%s is executable\n", path);
}
+4

stat , 0 (), . st_mode , , target - , , . , st_mode . ( , "" , "", " ".)

: , , , .

+4

stat? Psh. , .

access() syscall.

if (access(filename, F_OK|X_OK) == 0)
{
    /* You can execute this file. */
}

, . execve, - , , .. , . , , .

+4

?

execlp execvp.

0

access() . stat, /etc/group, , BESIDE getgid(), .

0

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


All Articles