ozma
ozma

Reputation: 399

execve(...) does not execute program despite passing in PATH variable

I'm executing a simple shell program from the directory:

/home/user/shell.exe

Using the code below, I'm able to run files that are in the same folder as my shell executable, but am unable to run programs such as ls.exe.

The tokens container includes the file name as the first element and any subsequent tokens (such as "-l" in the input "ls.exe -l") in the following elements.

if (fork())
{
  int status;
  wait(&status);
}
else
{
std::vector<const char*> exeArgs;
std::vector<const char*> envArgs;

std::for_each(tokens.begin(), tokens.end(),
[&exeArgs](const string& elem){ exeArgs.push_back(elem.c_str()); }
             );

exeArgs.push_back(nullptr);

string path = "PATH=";
path.append(getenv("PATH"));

envArgs.push_back(path.c_str());
envArgs.push_back(nullptr);

if (execve(exeArgs[0], const_cast<char *const *>(&exeArgs[0]),
                       const_cast<char *const *>(&envArgs[0])))
{
  std::cout << word << ": command not found" << std::endl;
  exit(0);
}
}

I've spent countless hours just googling and reading the man pages over and over but can't seem to get a clue why this code doesn't work.

The idea is that my shell program should allow users to set the PATH variable and then execute programs with that PATH variable, which is why I have to make execve() work properly instead of just using execvp().

I have a map of shell variables in a separate part of the file but since I can't even get this to work, I thought it would be pointless to include that.

Upvotes: 2

Views: 1485

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

You do know that the exec family of functions replaces the current process with the image of the new program? That's why it's so common to use fork before exec.

Armed with that knowledge, it's easy to find a solution for you, and how you can use execvp (which you need to use, execve doesn't really use the environment you pass, it just passes it along to the new program): You fork and use setenv to set the PATH of the new process, before calling execvp.

Upvotes: 5

Related Questions