Ahmed El-Gamal
Ahmed El-Gamal

Reputation: 190

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:

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

Upvotes: 0

Views: 1974

Answers (2)

kjohri
kjohri

Reputation: 1224

which command gives the complete path of a command. For example,

$ which ls
/bin/ls

So, you can do something like this in a C program,

system ("which ls >x");
// read file x for complete path of ls

Upvotes: 3

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

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

Upvotes: 2

Related Questions