Skip to content
Advertisement

How to get Linux command location in C?

I am using execv in C, but it demands to get the path of the command to get it executed, For example:

  • To execute ls I must have char* command = "/bin/ls";
  • To execute gedit I must have char* command = "/usr/bin/gedit";

My question is how to get the string "/bin" or "/usr/bin" in C ?

Advertisement

Answer

You can get the PATH variable from the environment. Then you parse it to get each component, then check in the location of each component whether the given command (file) exists there.

This is basically what the which command does. Source code of linux utilities can be found on-line

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement