Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a Unix shell in C: check if file is executable

Tags:

c

unix

I am working on implementing a Unix shell in C and I'm currently dealing with the problem of relative paths. Notably while inputting commands. For now I have to enter the full path of the executable every time, when I would much rather simply put "ls" or "cat".

I have managed to get the $PATH env variable. My idea is to split the variable at the ":" character, then append each new string to the command name and check if the file exists and is executable.

For example if my PATH is: "/bin:/usr/bin" and I input "ls", I would like the program to check first if "/bin/ls" exists and is executable, if not move on to "/usr/bin/".

Two questions:

1) Is it a good way to do it? (Doesn't it have to be necessarily the best. I just want to make sure that it would work.

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

I hope I'm clear enough, and ... well thanks :)

like image 526
rahmu Avatar asked Nov 28 '22 18:11

rahmu


1 Answers

Don't. Performing this check is wrong; it's inherently subject to a race condition. Instead, try executing it with the appropriate exec-family call. If it's not executable, you'll get an error.

Also note that you don't need to search the PATH yourself; execvp can do this for you.

like image 190
R.. GitHub STOP HELPING ICE Avatar answered Dec 06 '22 09:12

R.. GitHub STOP HELPING ICE