I’m writing a simple shell in C.
To execute a command, a shell basically creates a child process and subsequently execs the same to run the command.
I am using the function execve as follows:
execve(argList[0],argList,envList);
Here argList and envList are char*(string) arrays with (say) the following values:
argList={"ls",NULL}
envList={"/bin",NULL}
I figure that since ls is present as an executable in /bin directory, the required exec should have the same effect as ls (on a LINUX system ofcourse).
The execve command however is not able to execute for executables present in directories in the environment.
The same works perfectly for running executables in the current working directory.
Where am I going wrong?
Conclusion: I had mistaken environment to be entirely something else. [apologies :)]
The environment array is responsible for setting the environment for the child process.
Thus, as pointed out by Jim, the correct procedure is to set the environment variables in the format:
envList = { "HOME=/root", PATH="/bin:/sbin", NULL }
as is also explained here.
Further, in order to achieve the above mentioned result using execve (instead of execvp),
as Nemo explains, we could always make repeated calls to the directories in PATH. execve would fail if the file doesn’t exist.
This is incorrect.
envListprovides the environment strings for theexec-ed program; it is not a search list or a path list. A correctenvListwould be more like