cunixdirectoryexecvrealpath

How to get directory of exec files of any commands on terminal in C?


I am rewriting the problem since it's not clearly understood as far as I see. I implement my own shell in C which needs to support all commands the original one does.

The problem is to execute all existing UNIX bash commands in C without using execvp() or system() functions which already let you do that easily.

To do that, I need to search all required directories which may consist any kind of UNIX commands. I just want to know that:

Do I really be sure that I support all possible UNIX commands in any distribution when I checked all directories in my PATH environment variable? (which becomes /bin/, /usr/bin/, /usr/local/bin in my machine)

I have also found a method which gets the full directory of a file you inserted called realpath() . But unfortunately, it returns (null) when I attempt to get the directory of the command inserted in my own shell.

What else do you suggest me to achieve this problem? As a last solution, does it make sense to search whole computer recursively from the root to find the command inserted?

If there's something unclear, please let me know to clarify. I would be very thankful if you could answer with a piece of example code and clear [on hold] tag in the question if you think it's clearly described from now.

Thanks in advance!


Solution

  • First, note that realpath() doesn't search anything, it just determines the absolute path of a given file.

    There is no all possible UNIX command as you may think. At least any executable file can be considered as UNIX command, and executables are not necessarily the ones that have x right attached to it. Shell scripts may be executed by command like sh myscript even if executable access is not granted on it. Only binaries necessitate to have that attached right to be executed natively. So there is no true criterion that can help you. But you may have files that have x right and that are not executables!

    A common usage is that executables are located in some directories /bin, /usr/bin, /usr/local/bin, and alike. Your shell has an environnement variable named PATH that contains list of directories where to search for command you specified freely on command line.

    Anyway, if you choose a criterion to make an exhaustive search by yourself, say all files with x right then you can use command find like find some_starting_dir -perm +0111 to get all files that have x right somewhere.

    If you want to program it then you may use either legacy readdir() function or the newer nftw() to make your own directory traversal. You will find many example of these even on SO.